Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over dictionaries using 'for' loops

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?

like image 469
TopChef Avatar asked Jul 20 '10 22:07

TopChef


People also ask

How do you iterate over dictionaries using for loops?

Example 1: Access both key and value using items()The items() method should be used to loop through the dictionary's key and values. The items() method returns a list of tuples, each of which is a key-value pair. We can either iterate it directly or by using it along with the for loop.

Does looping over a dictionary using a for statement always iterate over its values?

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.

Can dictionaries be iterated in Python?

There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list. There is also items() method of dictionary object which returns list of tuples, each tuple having key and value.


2 Answers

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()).

like image 87
sberry Avatar answered Sep 16 '22 20:09

sberry


It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.

In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":

  • Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write

    for k in dict: ... 

    which is equivalent to, but much faster than

    for k in dict.keys(): ... 

    as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

  • Add methods to dictionaries that return different kinds of iterators explicitly:

    for key in dict.iterkeys(): ...  for value in dict.itervalues(): ...  for key, value in dict.iteritems(): ... 

    This means that for x in dict is shorthand for for x in dict.iterkeys().

In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.

like image 20
ars Avatar answered Sep 16 '22 20:09

ars