python: sorting an ordered dictionary

♀尐吖头ヾ 提交于 2021-01-27 13:57:09

问题


I create a dictionary:

d[1] = {'a':1, 'b':2}
d[2] = {'a':5, 'b':3}
d[3] = {'a':3, 'b':2}

I then try to sort by a field:

d = collections.OrderedDict(sorted(d.items(), key=itemgetter(1)))

so that I can output:

for key in d:
    print key, d[key]

This sorts on 'a', but I can't figure out how to sort on 'b'. How do I sort on 'b'?

EDIT: I'm not sure how this is unclear. I'd like to sort so that the output is ordered by the values in field 'b'.


回答1:


Modify your key function so that it explicitly returns the b value.

d = collections.OrderedDict(sorted(d.items(), key=lambda (key, value): value['b']))

Edit: apparently 3.X doesn't like tuple unpacking in lambdas, so you may have to resort to the longer way:

d = collections.OrderedDict(sorted(d.items(), key=lambda key_value_pair: key_value_pair[1]['b']))


来源:https://stackoverflow.com/questions/26533666/python-sorting-an-ordered-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!