Sort list of nested dictionaries by value

时间秒杀一切 提交于 2021-02-11 14:20:42

问题


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']))

So, i have the error:

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'

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.


回答1:


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']
    )
)

Out:

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

Note:

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']
    )
)



回答2:


If you want to handle an arbitrary amount of nested dictionaries, you could use a recursive function to sort the values:

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))

Output:

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


来源:https://stackoverflow.com/questions/65008509/sort-list-of-nested-dictionaries-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!