sorting - Python: sort this dictionary (dict in dict) -
d = { 'a':{'k':1, 'b':'whatever'}, 'b':{'k':2, 'b':'sort k'} } want sort dictionary k descending order, in python.
little tricky, please help.
dicts unordered. there no way sort them directly, if willing convert dict list of (key,value)-tuples, this:
in [9]: d out[9]: {'a': {'b': 'whatever', 'k': 1}, 'b': {'b': 'sort k', 'k': 2}} in [15]: sorted(d.items(),key=lambda x: x[1]['k'],reverse=true) out[15]: [('b', {'b': 'sort k', 'k': 2}), ('a', {'b': 'whatever', 'k': 1})] this excellent mini-howto explains use of key parameter.
Comments
Post a Comment