1

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'}]} ```



5
  • That's some invalid syntax with the [0: there Commented Dec 9, 2021 at 14:19
  • @Adam.Er8 you are right, i have corrected it, thanks! Commented Dec 9, 2021 at 14:27
  • Since dictionary entries aren't necessarily in any defined order… how do you want to map values from one to specific positions in the other…? Or don't you care about the particular order? Commented Dec 9, 2021 at 14:29
  • 2
    dict3 = {dict1[k]: v for k, v in dict2.items()}…? Commented Dec 9, 2021 at 14:30
  • @deceze int(dict1[k]) for an exact match to OPs expected output :) Commented Dec 9, 2021 at 14:33

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much, it is precisely what i wanted! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.