How to copy a dictionary and only edit the copy

前端 未结 20 2049
说谎
说谎 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条回答
  •  Happy的楠姐
    2020-11-21 07:40

    You can also just make a new dictionary with a dictionary comprehension. This avoids importing copy.

    dout = dict((k,v) for k,v in mydict.items())
    

    Of course in python >= 2.7 you can do:

    dout = {k:v for k,v in mydict.items()}
    

    But for backwards compat., the top method is better.

提交回复
热议问题