是不是你给的代码示例不准确。大概的给你写个例子:
# 字典的有序无序:https://www.cnblogs.com/yibeimingyue/p/9977164.html
# 情景1
dict0 = {'a': {'1': 1},
'c': {'3': 3},
'b': {'2': 2},
'd': {'5': 5}
}
dict0_keys = sorted(dict0.keys())
print(dict0_keys)
# ['a', 'b', 'c', 'd']
# 情景2
dict1 = {
'a': {'key': 3, 'value': 3},
'c': {'key': 2, 'value': 2},
'b': {'key': 1, 'value': 1},
'd': {'key': 5, 'value': 5}
}
dict1_keys = sorted(dict1, key=lambda item: dict1[item]['key'])
print(dict1_keys)
# ['b', 'c', 'a', 'd']
# 根据有有序的key,创建新的dict
dict2 = {}
for k in dict1_keys:
dict2.update({k: dict1.get(k)})
print(dict2)
# {'b': {'key': 1, 'value': 1}, 'c': {'key': 2, 'value': 2}, 'a': {'key': 3, 'value': 3}, 'd': {'key': 5, 'value': 5}}