Reputation: 129
When I was trying to understand Python dictionaries, I compared the output of two programs. I don't understand why the output is different.
Both programs start with
data = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}
First program:
for keys in data.items():
print keys
Second program:
for keys, values in data.items():
print keys, values
The outputs are
('key3', 'value3')
('key2', 'value2')
('key1', 'value1')
and
key3 value3
key2 value2
key1 value1
Why does the first output show parenthesised strings?
Why doesn't the second output show the commas?
Upvotes: 2
Views: 110
Reputation: 142106
dict.items
returns a sequence of 2-tuples, of (key, value).
What happens in the first example is that you're taking a single element from the that at at time, which in this case is the whole tuple (key, value). When you use for key, value in
Python performs "unpacking" which means it assigns the first element of that tuple to key to key and the next element to value, so you can access them as separate variables.
When you print those, Python prints a tuple (your first example), as (1, 2)
, but when it's unpacked and you print two separate variables, it prints the number 1
followed by the number 2
with a space in between.
Upvotes: 7
Reputation: 8610
dict.items
return a list of tuples of key, value pairs. If only one name in the for, it
assigns the tuple to the name. With two names, it unpacks the key, value to the names separately. See:
>>> a, b = (1, 2)
>>> a
1
>>> b
2
>>> a = (1, 2)
>>> a
(1, 2)
>>>
Upvotes: 6