2

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
ahajib
  • 12,838
  • 29
  • 79
  • 120
  • Do all your dicts only have one key-value pair? – cs95 Jan 08 '18 at 19:26
  • 2
    I don't think this is a dupe of that question because as OP said, the keys are different. – pault Jan 08 '18 at 19:34
  • 2
    @schwobaseggl, The situation looks different, although it's asking the same question. There's no keys in common. – Mangohero1 Jan 08 '18 at 19:34
  • 1
    @schwobaseggl This is completely a different question as I have described it in the text. I updated the title as well. – ahajib Jan 08 '18 at 19:36

2 Answers2

5
sorted(my_list,key=lambda x: list(x.values())[0][0])
Out[114]: [{'9564': [6, 'D']}, {'1200': [10, 'A']}, {'1000': [24, 'C']}]
BENY
  • 317,841
  • 20
  • 164
  • 234
4

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])
pault
  • 41,343
  • 15
  • 107
  • 149
  • `x.values()[0]` gives you the whole list, they just want to sort by the first element. – cs95 Jan 08 '18 at 19:33
  • 1
    You're absolutely right. Premature cut and paste- thanks for pointing that out. It's fixed now. – pault Jan 08 '18 at 19:36
  • Also, beware that `x.values()[0][0]` does not work on python3, since `.values()` doesn't return a list there. – cs95 Jan 08 '18 at 19:37