Categories
dictionary python

Iterating over dictionaries using ‘for’ loops

3937

d = {'x': 1, 'y': 2, 'z': 3}

for key in d:
    print(key, 'corresponds to', d[key])

How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is it simply a variable?

2

  • As we know that in Python Dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary. No, key is not a special word in Python. Here key is Just a variable name.

    Jan 10, 2021 at 4:26


  • 6

    did you try: for key, value in d.items():?

    Mar 16, 2021 at 22:11

6421

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

12

  • 226

    Adding an overlooked reason not to access value like this: d[key] inside the for loop causes the key to be hashed again (to get the value). When the dictionary is large this extra hash will add to the overall time. This is discussed in Raymond Hettinger’s tech talk youtube.com/watch?v=anrOzOapJ2E

    Jul 28, 2017 at 9:43

  • 7

    @HarisankarKrishnaSwamy what is the alternative?

    – JoeyC

    Nov 8, 2018 at 4:45

  • 11

    @yugr Why do you say that ? The docs says Keys and values are iterated over in insertion order. [docs.python.org/3/library/…

    – Geza Turi

    Jul 13, 2019 at 15:48

  • 3

    @GezaTuri Only starting from Python 3.6 (and there have been rumors this “feature” may be removed again in future versions).

    – yugr

    Jul 13, 2019 at 20:49

  • 25

    @yugr From Python 3.7, dictionaries are insertion-ordered and this is a language feature. See stackoverflow.com/a/39980744/9428564

    – Aimery

    Sep 9, 2019 at 14:54

518

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.

0

    257

    Iterating over a dict iterates through its keys in no particular order, as you can see here:

    (This is no longer the case in Python 3.6, but note that it’s not guaranteed behaviour yet.)

    >>> d = {'x': 1, 'y': 2, 'z': 3}
    >>> list(d)
    ['y', 'x', 'z']
    >>> d.keys()
    ['y', 'x', 'z']
    

    For your example, it is a better idea to use dict.items():

    >>> d.items()
    [('y', 2), ('x', 1), ('z', 3)]
    

    This gives you a list of tuples. When you loop over them like this, each tuple is unpacked into k and v automatically:

    for k,v in d.items():
        print(k, 'corresponds to', v)
    

    Using k and v as variable names when looping over a dict is quite common if the body of the loop is only a few lines. For more complicated loops it may be a good idea to use more descriptive names:

    for letter, number in d.items():
        print(letter, 'corresponds to', number)
    

    It’s a good idea to get into the habit of using format strings:

    for letter, number in d.items():
        print('{0} corresponds to {1}'.format(letter, number))
    

    1

    • 22

      From the Python 3.7 release notes: “The insertion-order preservation nature of dict objects is now an official part of the Python language spec.”

      Jul 18, 2018 at 16:30