"""
Given two dictionaries, find the keys they have in common,
and return a new dictionary that maps the corresponding values.
Example:
dict1 == {"a":"alpha", "d":"delta", "x":"xi"}
dict2 == {"b":"bet", "d":"dalet", "l":"lamed", "a":"alef"}
should return:
{"alpha":"alef", "delta":"dalet", "beta":"bet"}
"""
dict1 == {"a":"alpha", "d":"delta", "x":"xi"}
dict2 == {"b":"bet", "d":"dalet", "l":"lamed", "a":"alef"}
new_dict = {}
for key, value in dict1.items():
if value in new_dict:
new_dict[value].append(key)
else:
new_dict[value]=[key]
这就是我所拥有的,我所要做的就是使输出与{"alpha":"alef", "delta":"dalet", "beta":"bet"}
相同,这只是交换键。
根据你的问题,如果两个字典是这样的:
dict1= {"a":"alpha", "d":"delta", "x":"xi"}
dict2 == {"b":"bet", "d":"dalet", "l":"lamed", "a":"alef"}
comm_keys = set(dict1.keys()).intersection(dict2.keys())
required_dict = {dict1[key]: dict2[key] for key in comm_keys}
# Expected output : {'delta': 'dalet', 'alpha': 'alef'}
另一种方法是使用字典推导式
dict1 = {"a": "alpha", "d": "delta", "x": "xi"}
dict2 = {"b": "bet", "d": "dalet", "l": "lamed", "a": "alef"}
output = {dict1[x]: dict2[x] for x in dict1 if x in dict2}
{'alpha': 'alef', 'delta': 'dalet'}