【问题标题】:Sort list of nested dictionaries by value按值对嵌套字典列表进行排序
【发布时间】:2021-03-08 12:50:04
【问题描述】:

我有字典列表。我需要对其进行排序。如果这些字典中没有嵌套字典,那就很好了。但我需要对嵌套字典进行排序。

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'

但是如果我替换那些嵌套的字典,它会很顺利。 有一个答案如何按子键排序:sorting list of nested dictionaries in python 但我需要一种按键排序的方法。

【问题讨论】:

    标签: python json dictionary nested


    【解决方案1】:

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

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

    注意:

    如果您想在排序前跳过所有具有嵌套“年龄”的项目:

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

    【讨论】:

    • 如果我只想传递嵌套列表的内容怎么办?当我删除 else 语句时,我有无效的语法错误。与“else pass”用法相同的错误。
    • @glu:if/else 构造是所谓的“三元运算符”,因此它需要有一个 else 语句。您可能需要编辑您的问题以更清楚地说明您要做什么:'...传递嵌套列表的内容。'
    • 例如,如果我有字典列表并且字典里面有字典,但我不需要内部数据,所以我想跳过这个内部字典。
    【解决方案2】:

    如果您想处理任意数量的嵌套字典,可以使用递归函数对值进行排序:

    import sys
    from pprint import pp
    
    def getAge(d):
        if isinstance(d, dict):
            return getAge(d.get("age", None))
        elif isinstance(d, int):
            return d
        else:
            # An integer larger than any practical list or string index
            return sys.maxsize
    
    lis = [{"name": "Nandini", "age": {"name": "Nandini", "age": 20}},
           {"name": "Manjeet", "age": 21},
           {"name": "Valodja", "age": "NotANumber"},
           {"name": "Nikhil", "age": 19}]
    
    pp(sorted(lis, key=getAge))
    

    输出:

    [{'name': 'Nikhil', 'age': 19},
     {'name': 'Nandini', 'age': {'name': 'Nandini', 'age': 20}},
     {'name': 'Manjeet', 'age': 21},
     {'name': 'Valodja', 'age': 'NotANumber'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2016-04-30
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多