Home > OS >  Get list of dictionaries based on their key values
Get list of dictionaries based on their key values

Time:08-03

I have several dictionaries, let's say 5:

dict1={'Age': 20, 'Name': 'Bob'}
dict2={'Age': 10, 'Name': 'Ane'}
dict3={'Age': 40, 'Name': 'Lee'}
dict4={'Age': 50, 'Name': 'Rob'}
dict5={'Age': 30, 'Name': 'Sia'}

and

arr=[50,40,30,20,10]

Can I get a list of dictionaries based on the values of age in arr?

Desired output:

[dict4,dict3,dict5,dict1,dict2]

CodePudding user response:

Try using a lambda to sort by a certain property (in this case, Age):

Code:

dict1={'Age': 20, 'Name': 'Bob'}
dict2={'Age': 10, 'Name': 'Ane'}
dict3={'Age': 40, 'Name': 'Lee'}
dict4={'Age': 50, 'Name': 'Rob'}
dict5={'Age': 30, 'Name': 'Sia'}

dicts = [dict1, dict2, dict3, dict4, dict5]

dicts.sort(reverse=True, key=lambda x: x['Age'])

print(dicts)

Output:

[{'Age': 50, 'Name': 'Rob'}, {'Age': 40, 'Name': 'Lee'}, {'Age': 30, 'Name': 'Sia'}, {'Age': 20, 'Name': 'Bob'}, {'Age': 10, 'Name': 'Ane'}]

CodePudding user response:

Based on your comments:

arr = [50, 40, 30, 20, 10]

dicts = [dict1, dict2, dict3, dict4, dict5]

dicts = {d["Age"]: d for d in dicts}
dicts = [dicts[v] for v in arr]
print(dicts)

Prints:

[
    {"Age": 50, "Name": "Rob"},
    {"Age": 40, "Name": "Lee"},
    {"Age": 30, "Name": "Sia"},
    {"Age": 20, "Name": "Bob"},
    {"Age": 10, "Name": "Ane"},
]

CodePudding user response:

If the expected output is the dict names and not the values, you can create a mapping between Age and the dict name and iterate through arr and get the name of the dict by its age:

dict1 = {'Age': 20, 'Name': 'Bob'}
dict2 = {'Age': 10, 'Name': 'Ane'}
dict3 = {'Age': 40, 'Name': 'Lee'}
dict4 = {'Age': 50, 'Name': 'Rob'}
dict5 = {'Age': 30, 'Name': 'Sia'}

arr = [50, 40, 30, 20, 10]

age_to_dict_name = {globals()[x]['Age']: x for x in globals() if x.startswith("dict")}
expected_output = [age_to_dict_name[x] for x in arr]
print(expected_output)  # ['dict4', 'dict3', 'dict5', 'dict1', 'dict2']

  • Related