Asked : Nov 17
Viewed : 18 times
I am a bit puzzled by the following code:
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print (key, 'corresponds to', d[key])
What I don't understand is the key
portion. How does Python recognize that it needs only to read the key from the dictionary? Is key
a special word in Python? Or is it simply a variable?
Nov 17
key
is just a variable name.
for key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
For Python 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
To test for yourself, change the word key
to poop
.
In Python 3.x, iteritems()
was replaced with simply items()
, which returns a set-like view backed by the dict, like iteritems()
but even better. This is also available in 2.7 as viewitems()
.
The operation items()
will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value)
pairs, which will not reflect changes to the dict that happen after the items()
call. If you want the 2.x behavior in 3.x, you can call list(d.items())
.
answered Jan 25
When you iterate through dictionaries using the for .. in ..
-syntax, it always iterates over the keys (the values are accessible using dictionary[key]
).
To iterate over key-value pairs, use the following:
for k,v in dict.iteritems()
in Python 2for k,v in dict.items()
in Python 3answered Jan 25
I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:
d = {'x': 1, 'y': 2, 'z': 3}
for i, (key, value) in enumerate(d.items()):
print(i, key, value)
Note that the parentheses around the key, value are important, without them, you'd get an ValueError
"not enough values to unpack".
answered Jan 25
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.items():
print(key, value)
Output
a juice b grill c corn
key
and value
for iterable dt.items()
. items()
returns the key:value
pairs.key
and value
.answered Jan 25