How to make a copy of chained dicts effectively and nicely?

Steve D'Aprano steve+python at pearwood.info
Tue Sep 27 08:57:59 EDT 2016


On Tue, 27 Sep 2016 05:08 pm, Nagy Lc3a1szlc3b3 Zsolt wrote:

> #2. Much more effective version, but requires too many lines:
> 
> d= {}
> d.update(d1)
> d.update(d2)
> d.update(d3)

new_dict = {}
for d in (d1, d2, d3):
    new_dict.update(d)

Or, if you know for sure there's only three dicts:

new_dict = d1.copy()
new_dict.update(d2, **d3)


Or if you prefer:

new_dict = dict(d1)  # same as copying
new_dict.update(d2, **d3)




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list