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'.
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']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With