Iterating over dictionaries

suggest change

Considering the following dictionary:

d = {"a": 1, "b": 2, "c": 3}

To iterate through its keys, you can use:

for key in d:
    print(key)

Output:

"a"
"b"
"c"

This is equivalent to:

for key in d.keys():
    print(key)

or in Python 2:

for key in d.iterkeys():
    print(key)

To iterate through its values, use:

for value in d.values():
    print(value)

Output:

1
2
3

To iterate through its keys and values, use:

for key, value in d.items():
    print(key, "::", value)

Output:

a :: 1
b :: 2
c :: 3

Note that in Python 2, .keys(), .values() and .items() return a list object. If you simply need to iterate trough the result, you can use the equivalent .iterkeys(), .itervalues() and .iteritems().

The difference between .keys() and .iterkeys(), .values() and .itervalues(), .items() and .iteritems() is that the iter* methods are generators. Thus, the elements within the dictionary are yielded one by one as they are evaluated. When a list object is returned, all of the elements are packed into a list and then returned for further evaluation.

Note also that in Python 3, Order of items printed in the above manner does not follow any order.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Loops:
* Loops
* Iterating over dictionaries

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve