Skip to content Skip to sidebar Skip to footer

Dictionary Iterating -- For Dict Vs For Dict.items()

When we iterate over the dictionary below, each iteration returns(correctly) a key,value pair for key, value in dict.items(): print '%s key has the value %s' % (key, value)

Solution 1:

The first example is utilizing something known as "tuple unpacking" to break what is REALLY the same tuple as in your separate example down into two different variables.

In other words this:

for key, value indict.items():

Is just this:

for keyvalue in dict.items():
    key, value = keyvalue[0], keyvalue[1]

Remember that a for loop always iterates over the individual elements of the iterator you give it. dict.items() returns a list-like object of tuples, so every run through the for loop is a new tuple, automatically unpacked into key, value if you define it as such in the for loop.

It may help to think of it this way:

d = {'a':1, 'b':2, 'c':3}
list(d)          # ['a', 'b', 'c']             the keys
list(d.keys())   # ['a', 'b', 'c']             the keys
list(d.values()) # [1, 2, 3]                   the values
list(d.items())  # [('a',1), ('b',2), ('c',3)] a tuple of (key, value)

N.B. that the only reason your code

for key in dict.items():
    print"%s key has value: %s" % (key, value)

Does not throw a NameError is because value is already defined from elsewhere in your code. Since you do not define value anywhere in that for loop, it would otherwise throw an exception.

Solution 2:

In the second example you gave you are not assigning "value" to anything:

Notice the small edit here:

for key in dict:  ##Removed call to items() because we just want the key, ##Not the key, value pair
    value = dict[key]  # Added this lineprint"%s key has the value %s (key, value)

Note:

In the second example, you could now call dict.keys() or just dict (referencing a dictionary in a for loop will return it's keys). Calling dict.items() will confusingly assign key=(, ) which is probably not what you want.

Post a Comment for "Dictionary Iterating -- For Dict Vs For Dict.items()"