On Friday, December 5, 2014 3:20:14 PM UTC+8, Cameron Simpson wrote: > On 05Dec2014 15:01, telnetgm...@gmail.com <telnetgm...@gmail.com> wrote: > >Why the following code gives me errors??? And why the print statement run 2 > >times? I'll be appreciated your helps, thanks, > >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) > > Because of the line above. The return value of "sorted()" is a list. You > assign > that list to "addrnum_dict". That name now refers to the list from "sorted()". > > Because you call the orderaddrtimes() function twice, the second time you > call > it "addrnum_dict" is the list from the first call. Not a dict. > > You would be best to not assign the result of "sorte()" to "addrnum_dict". > Assign it to something else. > > > #addrnum_dict = OrderedDict(sorted(addrnum_dict.items(), key=lambda t: > > t[0])) > >if __name__ == '__main__': > > kinds = ["a","b"] > > for tmp_kind in kinds: > > orderaddrtimes() > > > >###################### > >errors: > >python aaa.py > ><type 'dict'> > ><type 'list'> > >Traceback (most recent call last): > > File "aaa.py", line 16, in <module> > > orderaddrtimes() > > File "aaa.py", line 11, in orderaddrtimes > > addrnum_dict = sorted(addrnum_dict.iteritems(), key=lambda d:d[1], > > reverse = True) > >AttributeError: 'list' object has no attribute 'iteritems' > > Thank you for including the complete error output. This is very helpful, and > often essential. > > Cheers, > Cameron Simpson <c...@zip.com.au> > > Who are all you people and why are you in my computer? - Kibo
Thanks for your help! I admit I have poor experience on python, and I careless also. Thanks! -- https://mail.python.org/mailman/listinfo/python-list