Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sort a nested list of dicts by key in python

Below is an example nested list of dictionaries. I want to order the lists by the number of points that Charlie has.

l = [[{'Name': 'Alice',   'Age': 40, 'Point': 80},
      {'Name': 'Bob',     'Age': 20             },
      {'Name': 'Charlie', 'Age': 30, 'Point': 10}],
     [{'Name': 'Alice',   'Age': 40, 'Point': 80},
      {'Name': 'Bob',     'Age': 20             },
      {'Name': 'Charlie', 'Age': 30, 'Point': 30}],
     [{'Name': 'Alice',   'Age': 40, 'Point': 80},
      {'Name': 'Bob',     'Age': 20             },
      {'Name': 'Charlie', 'Age': 30, 'Point': 20}]]

The output should look like this.

l = [[{'Name': 'Alice',   'Age': 40, 'Point': 80},
      {'Name': 'Bob',     'Age': 20             },
      {'Name': 'Charlie', 'Age': 30, 'Point': 10}],
     [{'Name': 'Alice',   'Age': 40, 'Point': 80},
      {'Name': 'Bob',     'Age': 20             },
      {'Name': 'Charlie', 'Age': 30, 'Point': 20}],
     [{'Name': 'Alice',   'Age': 40, 'Point': 80},
      {'Name': 'Bob',     'Age': 20             },
      {'Name': 'Charlie', 'Age': 30, 'Point': 30}]]

I think I should be able to use sorted() with the right arguments, but I’m not sure what the syntax would be.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sorted(l, key=lambda x: x[ ????? ])

Charlie is always the third item in the sublists.

>Solution :

If Charlie is always third, you could use this:

sorted(l, key=lambda x: x[2]['Point'])

Otherwise, you’d want to use a helper function:

def get_charlie_points(lst):
    for item in lst:
        if item['Name'] == 'Charlie':
            return item['Point']
    return 0  # Replace this with the number you want if there is no Charlie, or raise an exception

sorted(l, key=get_charlie_points)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading