开发者

Why doesn't mydict.items().sort() work?

When I try and sort开发者_如何学JAVA my dictionary, I get an error: ''nonetype' object is not iterable.

I am doing:

for k,v in mydict.items().sort():


The sort method returns None (it has sorted the temporary list given by items(), but that's gone now). Use:

for k, v in sorted(mydict.iteritems()):

Using .items() in lieu of .iteritems() is also OK (and needed if you're in Python 3) but, in Python 2 (where .items() makes and returns a list while .iteritems() doesn't, just returns an iterator), avoiding the making of an extra list is advantageous -- sorted will make its own list to return, anyway, without altering the argument passed to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜