DEV Community

Discussion on: How to Merge Two Dictionaries in Python

Collapse
 
prahladyeri profile image
Prahlad Yeri

Assuming you are going to discard the original dicts in favor of the merged one (which is typically the case in most situations), there is no need to "copy and update". You can simply run the update() method on one of the dicts and consider it the final which will be faster and efficient:

yusuke_power = {"Yusuke Urameshi": "Spirit Gun"}
hiei_power = {"Hiei": "Jagan Eye"}

hiei_power.update(yusuke_power)
powers = hiei_power

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

Yeah, that works too! Though, I’m not a huge fan of introducing an alias just for the sake of performance, but that’s just me.

Also, if we’re talking hypotheticals, it might be useful to maintain the old dictionaries since an update is going to overwrite any duplicate keys.