How to iterate though dictionary of dictionaries by nested dictionary value

Viewed 139

I don't think my title adequately describes what I am trying to do (nor do my Google searches), so I will give an example.

If I have the following dictionary of dictionaries:

employees = {'bill': {'wage' : 100000, 'dept' : 'finance'}, 
             'sandy' : {'wage' : 20000, 'dept' : 'hr'}, 
             'tom' : {'wage' : 1000000, 'dept' : 'vp'}}

Is it possible to loop through employees and sort by something like 'wage'?

i.e.

sorted_employees = sorted(employees.items(), key=lambda k: k['wage']) # Not this, but something like this
for key, value in employees.iteritems():
    print key, value

outputs

sandy {'wage': 20000, 'dept': 'hr'}
bill {'wage': 100000, 'dept': 'finance'}
tom {'wage': 1000000, 'dept': 'vp'}
1 Answers

you were super close! try

sorted_employees = sorted(employees.items(), key=lambda k: k[1]['wage'])

this works for python3, I think for python2 as well?

Related