簡體   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