![](/img/trans.png)
[英]Python dictionary with multiple keys pointing to same list in memory efficient way
[英]efficient way to combine keys with same values in python dictionary
例如,我有以下字典
{'key1':value1,'key2':value2,'key3':value1,.......}}
我想將其更改為以下形式:
{value1:[key1,key2],value2:[key3],....}
我編寫了以下內容來完成此任務。 但是,我不確定這是否是最好的方法。 有沒有更好的方法來執行此任務?
node_cluster = {}
for node,cluster in zip(partition.keys(),partition.values()):
if cluster not in node_cluster.keys():
node_cluster[cluster] = []
node_cluster[cluster].append(node)
您可以使用collections.defaultdict使代碼更短一些。 當您嘗試訪問尚不存在的鍵時, defaultdict(list)
將自動創建一個空列表作為值:
from collections import defaultdict
d = {'a': 1, 'b': 2, 'c': 1}
out = defaultdict(list)
for k, v in d.items():
out[v].append(k)
print(out)
# defaultdict(<class 'list'>, {1: ['a', 'c'], 2: ['b']})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.