问题
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