Sort List Of Dictionaries Based On Values Where Keys Have Different Names
I have a list of dictionaries which look like the following: my_list = [ {'1200' : [10, 'A']}, {'1000' : [24, 'C']}, {'9564' : [6, 'D']}, ]
Solution 1:
sorted(my_list,key=lambda x: list(x.values())[0][0])
Out[114]: [{'9564': [6, 'D']}, {'1200': [10, 'A']}, {'1000': [24, 'C']}]
Solution 2:
You can use values()
to access the dict
elements:
sorted(my_list, key=lambda x: x.values()[0][0])
Output:
[
{'9564': [6, 'D']},
{'1200': [10, 'A']},
{'1000': [24, 'C']}
]
This assumes that each entry contains a list with at least one element.
EDIT FOR PYTHON 3
As @cᴏʟᴅsᴘᴇᴇᴅ points out, values()
does not return a list in python3, so you'll have to do:
sorted(my_list, key=lambda x: list(x.values()[0])[0])
Post a Comment for "Sort List Of Dictionaries Based On Values Where Keys Have Different Names"