Python - 寻找一种更有效的方法来重新编号我的字典中的键



这是我目前的字典:

{0: [(1,1.0)],
1: [(132,1.0)],
2: [(2000,1.0)],
3: [(234,1.0)]}

现在,在某些情况下,我可能不得不放下这些键。让我们以 2 为例,生成的字典如下所示:

{0: [(1,1.0)],
1: [(132,1.0)],
3: [(234,1.0)]}

现在,我想对键重新编号,以便它们始终增加 1:

{0: [(1,1.0)],
1: [(132,1.0)],
2: [(234,1.0)]}

我的第一个想法是遍历字典并替换键,但考虑到我的实际字典有 2000 个键,这似乎不是最有效的途径。

有没有更有效的方法?

D = dict(enumerate(D[x] for x in sorted(D)))

但请使用列表。它按编号编制索引并自动重新编号:

>>> L = [
...    [(1,1.0)],
...    [(132,1.0)],
...    [(2000,1.0)],
...    [(234,1.0)]
... ]
>>> del L[1]
>>> print(L)
[
[(1,1.0)],
[(2000,1.0)],
[(234,1.0)]
]

您可以使用L = [D[x] for x in sorted(D)]将字典转换为列表 并使用D = dict(enumerate(L))转换回您的字典格式

所以这可以是一个解决方案:

D = dict(enumerate(D[x] for x in sorted(D)))

但最好首先使用列表。

>>> current = {0: [(1,1.0)],
...      1: [(132,1.0)],
...      3: [(234,1.0)]}
>>> new_dict = {}
>>> for i,key in enumerate(sorted(original.keys())):
...     new_dict[i] = a[key]
>>> new_dict
{0: [(1,1.0)],
1: [(132,1.0)],
2: [(234,1.0)]}

可能值得一试,可能会解决您的问题 OrderedDict

from collections import OrderedDict
d={0: [(1,1.0)],
1: [(132,1.0)],
3: [(234,1.0)],
-1:[(234,1.0)]} # added out of order case
od =OrderedDict(sorted(d.items()))
dict(zip(range(len(od)),od.values()))

输出:

{0: [(234, 1.0)], 1: [(1, 1.0)], 2: [(132, 1.0)], 3: [(234, 1.0)]}

最新更新