[英]Python Dictionary: Compare keys with Values of All Keys
我正在解決一個問題,該問題要求我比較包含單詞作為鍵和單詞列表作為值的字典中的元素。 請參見下面的示例。
test_dict={'cubed': ['zryba', 'aszcb', 'btadc', 'melon', 'ewdgf'],
'melon': ['jbilk', 'kcjml', 'cubed', 'nfmpo', 'ognqp'],
'poop': ['mllm', 'nmmn', 'onno', 'qppq', 'rqqr']}
我想返回一個新字典,其中包含與字典中其他鍵的值匹配的鍵。 我的以下代碼是錯誤的,我認為是因為它僅獨立考慮每個鍵值對,並且僅比較這些對中的項。 有沒有一種方法可以遍歷鍵以獲得所需的結果? 我想要的結果如下所示。
def find_matches(dict1):
match_dict={}
for key, value in dict1.items():
for word in value:
if key == word:
#rotate_dict[key]=word
match_dict[key].append(word)
return match_dict
find_matches(SO_example) #returns {}, but should return {'cubed':'melon','melon':'cubed'}
謝謝您的幫助。
以下對我有用:
test_dict={'cubed': ['melon', '2', '3', '4', '5'],
'melon': ['2', 'poop', '4', '5', '6'],
'poop': ['3', '4', '5', '6', 'cubed']}
d = defaultdict(str)
# iterate over keys and values
for key, values in test_dict.items():
# iterate over values
for val in values:
# if val is a key
if val in [x for x in test_dict.keys() if x != key]:
# set dict[key] = val
d[key] = val
print(d)
defaultdict(<class 'str'>, {'melon': 'poop', 'poop': 'cubed', 'cubed': 'melon'})
本質上,您將根據鍵列表檢查所有值,當前鍵除外。 如果希望返回的字典包含多個值,請使用列表或集合:
defaultdict(list) or defaultdict(set)
並附加值
d[key].append(val) or d[key].add(val)
如果您的問題陳述正確,那么您的麻煩就在於您的test_dict
是一個字典, test_dict
字符串映射到列表列表,而不是將它們映射到單詞列表。
您的find_matches
函數遍歷字典,將字符串key放入key
而將list-of-words放入value
。
然后,您嘗試迭代value
。 但是,如果將value
設置為
[['gum', 'glove', 'knee']]
然后當你做
for word in value:
可變word
將取值為['gum', 'glove', 'knee']
,然后循環將結束,因為value
僅包含一個元素-三個單詞的子列表。
您可以通過打印key
然后在循環中打印每個word
來確認這一點-我希望您只會看到一行帶有單詞列表的行。
要解決此問題,理想情況下,您將更改字典的格式。 為什么要存儲1個單詞列表? 為什么不直接存儲單詞列表呢?
如果由於某種原因無法做到這一點,那么您將需要決定如何進行:如果有多個單詞列表,您是否要全部掃描它們,還是僅掃描第一個這樣的列表?
# Scan the first list:
for word in value[0]:
...
# Scan all the lists:
for sublist in value:
for word in sublist:
...
嘗試:
test_dict = {'bat': [['gum', 'glove', 'knee']],
'crowd': [['big', 'nice', 'large']],
'glove': [['mitt', 'ball', 'bat']]}
def find_matches(dict1):
match_dict = {}
base_keys = dict1.keys()
for key, values in dict1.items():
for words in values:
for base_key in base_keys:
if base_key in words:
match_dict.update({key: base_key})
return match_dict
print(find_matches(test_dict)) #{'bat': 'glove', 'glove': 'bat'}
多for
是因為你有一個[['mitt', 'ball', 'bat']]
二維名單。
使用set可能更清楚
您在dict中發布沒有示例值的另一個示例dict,sol很簡單,刪除一個for
:
test_dict={'cubed': ['zryba', 'aszcb', 'btadc', 'melon', 'ewdgf'],
'melon': ['jbilk', 'kcjml', 'cubed', 'nfmpo', 'ognqp'],
'poop': ['mllm', 'nmmn', 'onno', 'qppq', 'rqqr']}
def find_matches(dict1):
match_dict = {}
base_keys = dict1.keys()
for key, values in dict1.items():
for base_key in base_keys:
if base_key in values:
match_dict.update({key: base_key})
return match_dict
print(find_matches(test_dict)) #{'cubed': 'melon', 'melon': 'cubed'}
您實際上可以通過dict理解來解決此問題。 您只需要遍歷test_dict
的名稱和列表,直到找到同時存在於dict和列表中的名稱:
>>> {n1:n2 for n1 in test_dict for n2 in test_dict[n1] if n2 in test_dict}
{'cubed': 'melon', 'melon': 'cubed'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.