'I do not understand how to switch keys while using two dictionaries
"""
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]
This is what I have, all I have to do is make it so that the output is what is the same as {"alpha":"alef", "delta":"dalet", "beta":"bet"}
which is just switching the keys.
Solution 1:[1]
According to your question if two dictionaries are like this:
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'}
Solution 2:[2]
One more way which you can do this is to use dictionary comprehension
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'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Deepak Tripathi |
Solution 2 | dassum |