1
votes

In python3, I have 2 dictionaries, dict1 and dict2 that are both populated with key/value pairs. I want to create a new dictionary dict3 and add both dict1 and dict2 as nested dictionaries to it. I cant BELIEVE how much time Ive wasted trying to google a solution. I find tutorial after tutorial about how to create nested dictionaries from scratch but nothing about adding an existing dictionary nested to another dictionary.

1
What do you mean by nested dictionaries? What do you want to be the keys of dict3?nog642

1 Answers

0
votes

IIUC:

dict1={1:2,3:4}
dict2={5:6,7:8}
dict3=dict(list(dict1.items())+[('dict2', dict2)])

print(dict3)

Output:

{1: 2, 3: 4, 'dict2': {5: 6, 7: 8}}

Or if you want to add the two dictionary:

dict1={1:2,3:4}
dict2={5:6,7:8}
dict3=dict([('dict1', dict1)]+[('dict2', dict2)])

print(dict3)
#Output:
#{'dict1': {1: 2, 3: 4}, 'dict2': {5: 6, 7: 8}}

Another ways:

#first scenario
dict1={1:2,3:4}
dict2={5:6,7:8}
dict3={**dict1}
dict3.update({'dict2':dict2})
print(dict3)
#Output:
#{1: 2, 3: 4, 'dict2': {5: 6, 7: 8}}

#second scenario
dict1={1:2,3:4}
dict2={5:6,7:8}
dict3={}
dict3.update({'dict1':dict1,'dict2':dict2})
print(dict3)
#Output:
#{'dict1': {1: 2, 3: 4}, 'dict2': {5: 6, 7: 8}}