Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

'some key' key has the value 'some value' (repeated however many times there are a k,v pair)

The above makes sense to me, however if we do this:

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

("some key", "some value") has the value "some value" (the left tuple will iterate through each key value pair and the right value will just stay at the first value in the dict and repeat)

We end up getting each k,v pair returned in the first %s (key) and the 2nd %s (value) does not iterate, it just returns the first value in the dict for each iteration of the for loop.

I understand that if you iterate with only for key in dict then you are iterating over the keys only. Here since we are iterating a set of tuples (by using dict.items()) with only the key in the for loop, the loop should run for the same number of times as the first example, since there are as many keys as key,value pairs.

What I'm having trouble grasping is why python gives you the entire tuple in the second example for key.


Thanks for the help all -- I'd like to add one more question to the mix.

for a,a in dict.items():
    print a

Why does the above print the value, and if i print a,a - obviously both values are printed twice. If I had typed for a,b I would be iterating (key,value) pairs so I would logically think I am now iterating over (key,key) pairs and would therefore print key rather than value. Sorry for the basic questions just playing around in interpreter and trying to figure stuff out.

like image 249
Solaxun Avatar asked Jul 14 '14 21:07

Solaxun


People also ask

Should I use dict () or {}?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Is iterating through a dictionary faster than a list?

Is iterating through a dictionary faster than a list? When it comes to 10,000,000 items a dictionary lookup can be 585714 times faster than a list lookup. 6.6 or 585714 are just the results of a simple test run with my computer.

Does dict items () return a list?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.

What does dict items () do in Python?

In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Parameters: This method takes no parameters. Returns: A view object that displays a list of a given dictionary's (key, value) tuple pair.


1 Answers

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 in dict.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.

like image 126
Adam Smith Avatar answered Sep 20 '22 10:09

Adam Smith