[英]python- searching dictionary sublists; converting dictionary keys to values
說我有以下字典(我正在使用的字典更多,更大):
dict1={1:["item", "word", "thing"], 2:["word", "item"], 3:["thing", "item", "item"]}
並將字典中使用的每個單詞存儲在列表中:
all_words=["item", "word", "thing"]
我想通過字典子列表運行列表中的每個單詞,並返回找到它們的所有子列表的鍵,將它們存儲在元組中。 所以我想得到:
dict2={"item":(1, 2, 3), "word":(1, 2), "thing":(1, 3)}
繼承人我所擁有的:
dict2={}
for word in all_words:
for key, sublist in dict2.items():
for word in sublist:
if word not in sublist:
dict2[word]=dict2[word]+key
else:
dict2[word]=key
因此,基於評論的固定程序將如下所示
>>> dict2 = {}
>>> for word in all_words:
... # Iterate over the dict1's items
... for key, sublist in dict1.items():
... # If the word is found in the sublist
... if word in sublist:
... # If the current word is found in dict2's keys
... if word in dict2:
... # Append the current key as a one element tuple
... dict2[word] += (key,)
... else:
... # Create a one element tuple and assign it to the word
... dict2[word] = (key,)
...
>>> dict2
{'item': (1, 2, 3), 'word': (1, 2), 'thing': (1, 3)}
如果你知道字典理解,那么同樣可以寫成
>>> {word: tuple(k for k, v in dict1.items() if word in v) for word in all_words}
{'item': (1, 2, 3), 'word': (1, 2), 'thing': (1, 3)}
整個元組創建邏輯,基於每個相應word
的dict1
,被擠壓為單個生成器表達式並轉換為帶元tuple(k for k, v in dict1.items() if word in v)
的元tuple(k for k, v in dict1.items() if word in v)
你的代碼的邏輯是不正確的,因為你只是迭代3個對象,而你只需要遍歷你的字典並反轉鍵和值的位置但是因為你可能有重復的值你可以使用set
容器來保存每個對應的鍵。名稱。 dict.setdefault
是這種情況的一個很好的工具:
>>> d={}
>>> for i,j in dict1.items():
... for k in j:
... d.setdefault(k,set()).add(i)
...
>>> d
{'item': set([1, 2, 3]), 'word': set([1, 2]), 'thing': set([1, 3])}
問題是你正在循環dict2.items
而它應該是dict1.items
。 如果找到,您dict2
鍵附加到dict2
值中,只需將值重新分配給dict1
值中的最后一個鍵dict1
。 因此dict2
值不是您所期望的。
相反,您也可以使用collections.defaultdict
(或使用@Kasra的解決方案,@ thefourtheye):
from collections import defaultdict
dict2 = defaultdict(tuple)
for word in all_words:
for key, sublist in dict1.iteritems(): # this
if word in sublist:
dict2[word] += (k,)
else:
dict2[word] = (k,)
dict2
Out[3]: defaultdict(<type 'tuple'>, {'item': (1, 2, 3), 'word': (1, 2), 'thing': (1, 3)})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.