I want to sort a list of dictionaries.
The problem is that key in the dictionaries are not same, but every dictionary will have only one item for sure.
For example, [{'foo':39}, {'bar':7}, {'spam':35}, {'buzz':4}]
Here, key is the name of the person and value is the age.
I want result as [{'buzz': 4}, {'bar': 7}, {'spam': 35}, {'foo': 39}]
What I am doing is :
def get_val(d): for k, v in d.items(): return v sorted_lst = sorted(lst, key=lambda d: get_val(d))
Is there any better solution?
Advertisement
Answer
You can use values of dict
in lambda
like below :
>>> lst_dct = [{'foo':39}, {'bar':7}, {'spam':35}, {'buzz':4}] >>> sorted(lst_dct, key=lambda x: list(x.values())) [{'buzz': 4}, {'bar': 7}, {'spam': 35}, {'foo': 39}]
You can extent this for use list with multi elements:
>>> lst_dct = [{'foo':[39, 40]}, {'bar':[7,8]}, {'spam':[4,5]}, {'buzz':[4,6]}] >>> sorted(lst_dct, key=lambda x: sorted(x.values())) [{'spam': [4, 5]}, {'buzz': [4, 6]}, {'bar': [7, 8]}, {'foo': [39, 40]}]