Reputation:
For example:
I have two dictionaries:
dict1 = {'machine1': {'operative_system': 'Windows', 'Description':'This is an example'} 'machine2': {'operative_system': 'Ubuntu', 'Description':'This is another example'}}
dict2 = {'machine1': {'Disk1': {'Name_disk':'example'}, 'Disk2': {'Name_disk':'disk2'}}}
How can I insert those "disks" into the first dictionary?
The names of the machines are the same...
Upvotes: 1
Views: 95
Reputation: 117951
You could use dict.update
to update the existing sub-dictionaries from dict1
, and wrap in a try/except
to handle KeyError
when not in dict2
for key, value in dict1.items():
try:
value.update(dict2[key])
except KeyError:
continue
Afterwards
>>> dict1
{'machine1': {'operative_system': 'Windows',
'Description': 'This is an example',
'Disk1': {'Name_disk': 'example'},
'Disk2': {'Name_disk': 'disk2'}},
'machine2': {'operative_system': 'Ubuntu',
'Description': 'This is another example'}}
Similarly the following would also work
for key, value in dict1.items():
if key in dict2:
value.update(dict2[key])
Upvotes: 1