繁体   English   中英

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

[英]Python - Looking for a more efficient way to renumber the keys in my dictionary

这是我当前的字典:

{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))转换回dict格式

这样可以解决:

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)]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM