[英]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.例如,
[{'foo':39}, {'bar':7}, {'spam':35}, {'buzz':4}]
这里,key 是人名,value 是年龄. I want result as [{'buzz': 4}, {'bar': 7}, {'spam': 35}, {'foo': 39}]
What I am doing is :我希望结果为
[{'buzz': 4}, {'bar': 7}, {'spam': 35}, {'foo': 39}]
我正在做的是:
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 :您可以在
lambda
使用dict
值,如下所示:
>>> 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]}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.