Path: csiph.com!usenet.pasdenom.info!news.albasani.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Dan Sommers Newsgroups: comp.lang.python Subject: Re: dict turn to list unexpected at runtime??? Date: Fri, 5 Dec 2014 07:15:13 +0000 (UTC) Organization: A noiseless patient Spider Lines: 24 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injection-Date: Fri, 5 Dec 2014 07:15:13 +0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="7afa85ad1f051434641aa58aa18198d3"; logging-data="8961"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX191CwzGTjCSGcbl4/fLz0JvKPnf9dRsoIM=" User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508 git://git.gnome.org/pan2) Cancel-Lock: sha1:ktMcws0pR3LLxLdyOuJU9uauF2M= Xref: csiph.com comp.lang.python:81981 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