Dictionary is really not easy to handle

Peter Otten __peter__ at web.de
Thu Apr 28 05:17:23 EDT 2016


jfong at ms4.hinet.net wrote:

> I have a dictionary like this:
> 
>>>> dct ={1: 'D', 5: 'A', 2: 'B', 3: 'B', 4: 'E'}
> 
> The following code works:

> But...this one?
> 
>>>> for k,v in dct: print(k,v)
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'int' object is not iterable
> 
> No idea what the error message means:-( Can anyone explain it? Thanks
> ahead.

for k, v in items: ...

is basically a shortcut for

for x in items:
    k, v = x


The assignment with multiple names on the left side triggers what is called 
"unpacking", i. e.

k, v = x

is basically a shortcut for

it = iter(x)
try:
    k = next(it)
    v = next(it)
except StopIteration:
    raise ValueError # not enough items
try:
   next(it) # too many item if this succeeds
except StopIteration:
   pass
else
   raise ValueError

Now remember that in

for x in dct: ...

x is actually the key and only the key -- an int in your example dict. 
Then

iter(x)

raises the exception you saw:

>>> iter(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

If x were (for example) a string this would succeed

it = iter("some string")

as you can iterate over the string's characters -- but you'd get a 
ValueError for string lengths != 2:

>>> k, v = ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
>>> k, v = "ab"
>>> k
'a'
>>> v
'b'
>>> k, v = "abc"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

With that information, can you predict what

for k, v in {(1, 2): "three"}: print(k, v)

will print?





More information about the Python-list mailing list