Reputation: 11
I have two dictionaries, and i would like to create a third where the values from number 1 becomes the keys in number 2 - i have searched alot but i think since my second dictionary is in a nested form i have not seemed to find an example. I am new to python, which maybe is why i have searched for the wrong things, and i hoped that posting here could help me solve it.
dict1 = {0: '123', 1: '456', 2:'789'}
dict 2 =
{0: [{'id': 'abcd',
'ocid': '134'},
{'id': 'efgh',
'ocid': '154'}],
1: {'id': 'rfgh',
'ocid': '654'},
{'id': 'kjil',
'ocid': '874'}],
2: {'id': 'bgsj',
'ocid': '840'},
{'id': 'ebil',
'ocid': '261'}]}
My desired output is:
dict3 =
{123: [{'id': 'abcd',
'ocid': '134'},
{'id': 'efgh',
'ocid': '154'}],
456: {'id': 'rfgh',
'ocid': '654'},
{'id': 'kjil',
'ocid': '874'}],
789: {'id': 'bgsj',
'ocid': '840'},
{'id': 'ebil',
'ocid': '261'}]} ```
Upvotes: 1
Views: 40
Reputation: 1709
As long as the two dictionaries are the same length and in the expected order to make the matches, you can iterate through the pairs of values in both dictionaries as follows:
keys = dict1.values() # Get values from dict1
values = dict2.values() # Get values from dict2
dict3 = {} # Init new dict
# Iterate over tuples (dict1_value, dict2_value)
for key, value in zip(keys, values):
dict3[key] = value # Use dict1_value as key and dict2_value as value
EDIT
Extending my original answer with @deceze suggestion for the case when key in both dictionaries can be used to perform the matches:
dict3 = {dict1[k]: v for k, v in dict2.items()}
I hope this works for you!
Upvotes: 1