Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: sorting an ordered dictionary

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'.

like image 967
foosion Avatar asked Jan 09 '23 13:01

foosion


1 Answers

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']))
like image 189
Kevin Avatar answered Jan 17 '23 07:01

Kevin