I have the received a dictionary that looks like this:
{('M6.9', 'M31.467', 'M3.733'): '2',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): '2',
('M29', 'M23.59'): '2'}
I have created a second dictionary to decode it like so:
{('M6.9', 'M31.467', 'M3.733'): 'bedrooms',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): 'toilets',
('M29', 'M23.59'): 'occupants'}
How can I recode my first dictionary with my second dictionary, so that I get as output a dictionary that looks like this?
{'bedrooms': '2',
'toilets': '2',
'occupants': '2'}
CodePudding user response:
You can do it like this:
a = {('M6.9', 'M31.467', 'M3.733'): '2',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): '2',
('M29', 'M23.59'): '2'}
b = {('M6.9', 'M31.467', 'M3.733'): 'bedrooms',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): 'toilets',
('M29', 'M23.59'): 'occupants'}
c = {}
for k,v in b.items():
c[v] = a[k]
print(c)
{'bedrooms': '2', 'toilets': '2', 'occupants': '2'}
CodePudding user response:
You can write a function which iterates over the keys of the dictionaries, since they are the same:
def recodeDict(dict_names, dict_numbers):
new_dict = {}
for key in dict_names:
new_dict[dict_names[key]] = dict_numbers[key]
return new_dict
You can also do it this way:
new_dict = {dict_names[key]: dict_numbers[key] for key in dict_names}
EDIT:
Combining that with Sagi's answer:
c = { v: a[k] for k,v in b.items()}