Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #81980 > unrolled thread
| Started by | "telnetgmike@gmail.com" <telnetgmike@gmail.com> |
|---|---|
| First post | 2014-12-05 15:01 +0800 |
| Last post | 2014-12-05 07:15 +0000 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
dict turn to list unexpected at runtime??? "telnetgmike@gmail.com" <telnetgmike@gmail.com> - 2014-12-05 15:01 +0800
Re: dict turn to list unexpected at runtime??? Dan Sommers <dan@tombstonezero.net> - 2014-12-05 07:15 +0000
| From | "telnetgmike@gmail.com" <telnetgmike@gmail.com> |
|---|---|
| Date | 2014-12-05 15:01 +0800 |
| Subject | dict turn to list unexpected at runtime??? |
| Message-ID | <mailman.16610.1417762972.18130.python-list@python.org> |
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)
#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'
[toc] | [next] | [standalone]
| From | Dan Sommers <dan@tombstonezero.net> |
|---|---|
| Date | 2014-12-05 07:15 +0000 |
| Message-ID | <m5rm21$8o1$1@dont-email.me> |
| In reply to | #81980 |
On Fri, 05 Dec 2014 15:01:51 +0800, telnetgmike@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
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web