![](/img/trans.png)
[英]python dictionary put values of keys into a list where the keys are in another list
[英]Best way to exchange keys with values in a dictionary, where values are in a list?
我的 dict ( cpc_docs
) 的結構類似於
{
sym1:[app1, app2, app3],
sym2:[app1, app6, app56, app89],
sym3:[app3, app887]
}
我的字典有 15K 個鍵,它們是唯一的字符串。 每個鍵的值是一個應用程序編號列表,它們可以顯示為多個鍵的值。
我看過這里 [ Python: Best Way to Exchange Keys with Values in a Dictionary? ,但由於我的值是一個列表,我得到一個錯誤unhashable type: list
我嘗試了以下方法:
res = dict((v,k) for k,v in cpc_docs.items())
for x,y in cpc_docs.items():
res.setdefault(y,[]).append(x)
new_dict = dict (zip(cpc_docs.values(),cpc_docs.keys()))
這些當然都不起作用,因為我的價值觀是列表。
我希望值列表中的每個唯一元素及其所有鍵都作為一個列表。
像這樣的東西:
{
app1:[sym1, sym2]
app2:[sym1]
app3:[sym1, sym3]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
一個好處是根據每個值列表的 len 對新的 dict 進行排序。 所以像:
{
app1:[sym1, sym2]
app3:[sym1, sym3]
app2:[sym1]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
您的setdefault
代碼幾乎就在那里,您只需要對值列表進行額外的循環:
res = {}
for k, lst in cpc_docs.items():
for v in lst:
res.setdefault(v, []).append(k)
new_list=[]
for k,v in cpc_docs.items():
for i in range(len(v)):
new_list.append((k,v[i]))
doc_cpc = defaultdict(set)
for tup in cpc_doc_list:
doc_cpc[tup[1]].add(tup[0])
可能有很多更好的方法,但這是有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.