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.
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)