【发布时间】: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