我正在解决一个问题,该问题要求我比较字典中的元素,该字典包含作为键的单词和作为值的单词列表。请参见下面的示例。
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)
