Dictionary is really not easy to handle

Rustom Mody rustompmody at gmail.com
Thu Apr 28 04:43:05 EDT 2016


On Thursday, April 28, 2016 at 1:57:40 PM UTC+5:30, jf... 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
> 
> and this one too:
> 
> >>> for k,v in dct.items(): print(k,v)
> ...
> 1 D
> 2 B
> 3 B
> 4 E
> 5 A
> 
> 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.

Yes thats an unkind error message
Wont try to explain it.
But lets remove it instead:

>>> dct ={(1,2): 'D', (4,5): 'A'}
>>> 
>>> for k,v in dct:
...   print (k,v)
... 
1 2
4 5
>>> 



More information about the Python-list mailing list