Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #81982
| Date | 2014-12-05 18:19 +1100 |
|---|---|
| From | Cameron Simpson <cs@zip.com.au> |
| Subject | Re: dict turn to list unexpected at runtime??? |
| References | <C98772F5-8013-498A-BB7B-54F4D8D27269@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.16611.1417763998.18130.python-list@python.org> (permalink) |
On 05Dec2014 15:01, telnetgmike@gmail.com <telnetgmike@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 <cs@zip.com.au>
Who are all you people and why are you in my computer? - Kibo
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: dict turn to list unexpected at runtime??? Cameron Simpson <cs@zip.com.au> - 2014-12-05 18:19 +1100 Re: dict turn to list unexpected at runtime??? telnetgmike@gmail.com - 2014-12-04 23:31 -0800
csiph-web