简体   繁体   中英

Sort list of dictionaries with inconsistent keys

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?

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]}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM