Dictionary is really not easy to handle

Steven D'Aprano steve at pearwood.info
Thu Apr 28 06:00:52 EDT 2016


On Thu, 28 Apr 2016 06:27 pm, 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:
> 
>>>> for k in dct: print(k, dct[k])
> ...
> 1 D
> 2 B
> 3 B
> 4 E
> 5 A

When you iterate over the dictionary, you get a single object each time, the
key. So you have:

    k = 1
    k = 2

etc. (It is a coincidence that they are in numeric order. That won't happen
for all dicts, in all versions of Python. Normally they are in arbitrary
order.)



> and this one too:
> 
>>>> for k,v in dct.items(): print(k,v)
> ...
> 1 D
> 2 B
> 3 B
> 4 E
> 5 A

When you iterate over the dictionary items, you get a *pair* of objects,
namely the key and the value in a tuple. So each time through the loop, you
have something like:

    k, v = (1, 'D') # a tuple with two items

which is equivalent to:

    k = 1  # first item
    v = 'D'  # second item


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

Remember that iterating over the dictionary gives you the keys alone. In
this case, the keys are *integers*, not strings or lists or tuples. So you
are asking Python to do this:

    k, v = 1

which you remember is equivalent to this:

    k = ???  # first item of int 1
    v = ???  # second item of int 1


What goes into the ??? on each line? You cannot split 1 into two items,
because it is not an iterable sequence (not a string, not a list, not a
tuple). What you are asking Python to do makes no sense, so it gives a
TypeError.


-- 
Steven




More information about the Python-list mailing list