按值对嵌套字典列表进行排序 [英] Sort list of nested dictionaries by value

查看:58
本文介绍了按值对嵌套字典列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字典清单.我需要对它进行排序.如果这些字典中没有嵌套的字典,那么它将运行良好.但是我需要对嵌套字典进行排序.

I have list of dictionaries. I need to sort it. If there is no nested dictionaries in those ones, it goes well. But i need to sort nested dictionaries.

lis = [{"name": "Nandini", "age": {"name": "Nandini", "age": 20}},
       {"name": "Manjeet", "age": 21},
       {"name": "Nikhil", "age": 19}]

# using sorted and lambda to print list sorted
# by age
print("The list printed sorting by age: ")
print(sorted(lis, key=lambda i: i['age']))

所以,我有错误:

Traceback (most recent call last):
  File "D:\json\111.py", line 8, in <module>
    print(sorted(lis, key=lambda i: i['age']))
TypeError: '<' not supported between instances of 'int' and 'dict'

但是,如果我替换那些嵌套字典,它会进行的很好.有一个如何按子项排序的答案:在python中嵌套字典的排序列表但是我需要一种方法来按键排序.

But if I replace those nested dictionary, it goes well. There is an answer how to sort by subkey: sorting list of nested dictionaries in python but i need a way how to sort by key.

推荐答案

您可以将或运算符与 if/else 结合使用以指定密钥:

You could work with an or operator in combination with if/else to specify the key:

print(
    sorted(
        lis,
        # Uses age if it is an integer else take the 'second level' age value
        key=lambda i: i['age'] if isinstance(i['age'], int) else i['age']['age']
    )
)

出局:

The list printed sorting by age: 
[{'name': 'Nikhil', 'age': 19}, {'name': 'Nandini', 'age': {'name': 'Nandini', 'age': 20}}, {'name': 'Manjeet', 'age': 21}]

注意:

如果您想跳过所有带有嵌套年龄"的项目,请在排序之前将其过滤掉:

In case you want to skip all items that have a nested 'ages' filter them out before sorting:

print(
    sorted(
        [item for item in lis if isinstance(item['age'], int)],
        key=lambda i: i['age']
    )
)

这篇关于按值对嵌套字典列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆