How do I merge dictionaries together in Python?

后端 未结 7 1789
无人及你
无人及你 2020-12-04 17:05
d3 = dict(d1, **d2)

I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I woul

7条回答
  •  春和景丽
    2020-12-04 17:49

    I believe that, as stated above, using d2.update(d1) is the best approach and that you can also copy d2 first if you still need it.

    Although, I want to point out that dict(d1, **d2) is actually a bad way to merge dictionnaries in general since keyword arguments need to be strings, thus it will fail if you have a dict such as:

    {
      1: 'foo',
      2: 'bar'
    }
    

提交回复
热议问题