Merge dictionaries without overwriting values

后端 未结 3 381
既然无缘
既然无缘 2021-01-22 00:42

it seems a simple task:

I am trying to merge 2 dictionaries without overwriting the values but APPENDING.

a = {1: [(1,1)],2: [(2,2),(3,3)],3: [(4,4)]}          


        
3条回答
  •  野的像风
    2021-01-22 01:43

    As an explanation of why your a changes, consider your loop:

    for k in a.keys():
        if k in all:
            all[k].append(a[k])
        else:
            all[k] = a[k]
    

    So, if k is not yet in all, you enter the else part and now, all[k] points to the a[k] list. It's not a copy, it's a reference to a[k]: they're basically the same object. At the next iteration, all[k] is defined, and you append to it: but as all[k] points to a[k], you end up also appending to a[k].

    You want to avoid a all[k] = a[k]. You could try that:

    for k in a.keys():
        if k not in all:
            all[k] = []
        all[k].extend(a[k])
    

    (Note the extend instead of the append, as pointed out by @Martijn Pieters). Here, you never have all[k] pointing to a[k], so you're safe. @Martijn Pieters' answer is far more concise and elegant, though, so you should go with it.

提交回复
热议问题