Home > Software engineering >  How to order list of dictionaries in python by a given value in sub-list of dictionaries?
How to order list of dictionaries in python by a given value in sub-list of dictionaries?

Time:01-20

I am having a list of dictionaries containing sub-list of dictionaries:

x = [{'id': '1', 'employe_id': 15, 'name': 'John', 'columns': [{'Age': '22', 'class': 'int'}, {'Salary': '2700', 'class': 'int'}]},
{'id': '2', 'employe_id': 11, 'name': 'Sara', 'columns': [{'Age': '19', 'class': 'int'}, {'Salary': '1800', 'class': 'int'}]},
{'id': '3', 'employe_id': 12, 'name': 'Anna', 'columns': [{'Age': '34', 'class': 'int'}, {'Salary': '3500', 'class': 'int'}]},
]

For examples sorting this list by Age or Salary

By Age I expect

x = [{'id': '2', 'employe_id': 11, 'name': 'Sara', 'columns': [{'Age': '19', 'class': 'int'}, {'Salary': '1800', 'class': 'int'}]}, {'id': '1', 'employe_id': 15, 'name': 'John', 'columns': [{'Age': '22', 'class': 'int'}, {'Salary': '2700', 'class': 'int'}]}, {'id': '3', 'employe_id': 17, 'name': 'Anna', 'columns': [{'Age': '34', 'class': 'int'}, {'Salary': '3500', 'class': 'int'}]}]

CodePudding user response:

Sort Using lambda.

x.sort(key=lambda i: int(i["columns"][0]["Age"]))
print(x)
  • Related