I have a dict as follows:
values = {'A1' : '123456', 'B1' : 123456, ....}
I know that the correct way to iterate through is:
for key, value in values.items():
#do what you want
By mistake, I forgot to add .items() and so I started getting strange KeyError
I tried printing and it was only getting the first character of each string and assigning it to key and value
My question is: why is python doing that? what is happening behind the scene?
When you write:
for x1,x2 in iterable:
# ...
that actually means you do sequence unpacking in Python. Python evaluates it like:
x1,x2 = key0
Where key0 is the first key (and of course other keys). This works if key0 is an iterable that has exactly two elements. In that case the first element is assigned to x1 and the second to x2.
Now a string is an iterable where its elements are the characters. So a string 'A1' has two elements: 'A' and '1'. This means that if you write:
key,value = 'A1'
key will hold 'A' and value will hold '1'. Now if you print key, it will thus print the first value of the key.
Using a for on a values.items() is no "magical expression": items() simply is an iterable that produces 2-tuples containing a key and the corresponding value. Since a tuple is also an iterable where the items are the elements of the tuple, the tuple is unpacked in the key and the value. So when you write: for key,value in values.items(), the .items() will generate a sequence like ('A1','123456'), ('B1',123456). Now if such tuple is assigned to key,value, it is like writing:
key,value = ('A1','123456')
so key will take the first element of the tuple ('A1') and value the second (123456).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With