【发布时间】:2020-01-22 07:56:16
【问题描述】:
对于如何仅使用其子键按字母顺序对嵌套字典进行排序真的很苦恼。我在这里找不到类似的问题。
例如我有:
people = {5: {'first': 'John', 'age': '27', 'last': 'Doe'},
2: {'first': 'Marie', 'age': '22', 'gender': 'Female'}}
但是想要:
people = {5: {'age': '27','first': 'John', 'last': 'Doe'},
2: {'age': '22','first': 'Marie', 'gender': 'Female'}}
尝试:
import OrderedDict from collections
for d in people:
people[d] = OrderedDict(sorted(d.items()))
AttributeError: 'int' object has no attribute 'items'
【问题讨论】:
-
请提及您尝试过的内容、进度和遇到的错误。见stackoverflow.com/help/how-to-ask
标签: python sorting dictionary collections nested