How to copy a dictionary and only edit the copy

前端 未结 20 1973
说谎
说谎 2020-11-21 06:59

Can someone please explain this to me? This doesn\'t make any sense to me.

I copy a dictionary into another and edit the second and both are changed. Why is this hap

相关标签:
20条回答
  • Copying by using a for loop:

    orig = {"X2": 674.5, "X3": 245.0}
    
    copy = {}
    for key in orig:
        copy[key] = orig[key]
    
    print(orig) # {'X2': 674.5, 'X3': 245.0}
    print(copy) # {'X2': 674.5, 'X3': 245.0}
    copy["X2"] = 808
    print(orig) # {'X2': 674.5, 'X3': 245.0}
    print(copy) # {'X2': 808, 'X3': 245.0}
    
    0 讨论(0)
  • 2020-11-21 07:58

    the following code, which is on dicts which follows json syntax more than 3 times faster than deepcopy

    def CopyDict(dSrc):
        try:
            return json.loads(json.dumps(dSrc))
        except Exception as e:
            Logger.warning("Can't copy dict the preferred way:"+str(dSrc))
            return deepcopy(dSrc)
    
    0 讨论(0)
提交回复
热议问题