gpt4 book ai didi

python - 将字典键更新为升序?

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:58 25 4
gpt4 key购买 nike

我有一本字典:

A = {'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {0: {'variable_1': 'xxx', 'variable_2': 'zzz'},
1: {'variable_1': 'yyy', 'variable_2': 'uuu'},
3: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}

我想让二级key自动提升像这样:

{'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {2: {'variable_1': 'xxx', 'variable_2': 'ppp'},
3: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {4: {'variable_1': 'xxx', 'variable_2': 'zzz'},
5: {'variable_1': 'yyy', 'variable_2': 'uuu'},
6: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}

最佳答案

常规词典是无序的,因此您需要使用 OrderedDict .

全局计数器变量可以跟踪条目总数。

sorted函数将获取键/值元组列表并根据键对它们进行排序。

>>> from collections import OrderedDict
>>> A = {'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {0: {'variable_1': 'xxx', 'variable_2': 'zzz'},
1: {'variable_1': 'yyy', 'variable_2': 'uuu'},
3: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}

>>> OA = OrderedDict()
>>> count = 0
>>> for animal, info in sorted(A.items()):
OA[animal] = OrderedDict()
for i, variables in sorted(info.items()):
OA[animal][count] = variables
count += 1

>>> OA
OrderedDict([
('cat', OrderedDict([(0, {'variable_2': 'yyy', 'variable_1': 'xxx'}),
(1, {'variable_2': 'kkk', 'variable_1': 'ttt'})])),
('dog', OrderedDict([(2, {'variable_2': 'ppp', 'variable_1': 'xxx'}),
(3, {'variable_2': 'www', 'variable_1': 'qqq'})])),
('fox', OrderedDict([(4, {'variable_2': 'zzz', 'variable_1': 'xxx'}),
(5, {'variable_2': 'uuu', 'variable_1': 'yyy'}),
(6, {'variable_2': 'jjj', 'variable_1': 'ccc'})]))
])

如果需要,您可以对最里面的变量进行排序,并将它们也存储在 OrderedDict 中。

关于python - 将字典键更新为升序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com