简体   繁体   中英

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']},
          ]

All dictionaries in the list have one key-value pair.

I want to sort it based on the first element of each dictionaries value which is a list, so the sorted list would look like:

my_list_sorted = [
          {'9564' : [6, 'D']},
          {'1200' : [10, 'A']},
          {'1000' : [24, 'C']},
          ]

As you can see the keys have different names and that's why I could not use answers from, for example, the following post: How do I sort a list of dictionaries by a value of the dictionary?

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])
sorted(my_list,key=lambda x: list(x.values())[0][0])
Out[114]: [{'9564': [6, 'D']}, {'1200': [10, 'A']}, {'1000': [24, 'C']}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM