dict turn to list unexpected at runtime???

Dan Sommers dan at tombstonezero.net
Fri Dec 5 02:15:13 EST 2014


On Fri, 05 Dec 2014 15:01:51 +0800, telnetgmike at gmail.com wrote:

> Why the following code gives me errors??? And why the print statement run 2 times? ...
> addrnum_dict = {'a':1,'b':2}
> def orderaddrtimes():
>     global addrnum_dict
>     print type(addrnum_dict)
> 
>     addrnum_dict = sorted(addrnum_dict.iteritems(), key=lambda d:d[1], reverse = True)
>     #addrnum_dict = OrderedDict(sorted(addrnum_dict.items(), key=lambda t: t[0]))
> if __name__ == '__main__':
>     kinds = ["a","b"]
>     for tmp_kind in kinds:
>         orderaddrtimes()

The print statement runs twice because you're calling orderaddrtimes
twice, once for "a" and once for "b."

addrnum_dict becomes a list when you bind it to the return value from
sorted on the first call to orderaddrtimes; you get the error on the
second call.

HTH,
Dan



More information about the Python-list mailing list