Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

python - Why doesn't deepcopy work on this dictionary?

How to achieve deepcopy in dictionaries?

My original code :

li1 = ['Column_6', 'Column_11']
delimiters = ['a','b','c','d']
inner_dict = dict.fromkeys(delimiters,[0,0])
delim_dict = dict.fromkeys(li1 ,None)
for k,v in delim_dict.items():
    delim_dict[k] = copy.deepcopy(inner_dict) 

print (delim_dict) gives

{'Column_6': {'a': [0, 0], 'b': [0, 0], 'c': [0, 0], 'd': [0, 0]},
 'Column_11': {'a': [0, 0], 'b': [0, 0], 'c': [0, 0], 'd': [0, 0]}}
delim_dict['Column_6']['a'][0]=5
print (delim_dict)

gives

{'Column_6': {'a': [5, 0], 'b': [5, 0], 'c': [5, 0], 'd': [5, 0]},
 'Column_11': {'a': [0, 0], 'b': [0, 0], 'c': [0, 0], 'd': [0, 0]}}

Why keys b,c,d are updated with [5, 0] in spite of deepcopy?

I am able to achieve result with the Modified code :

li1 = ['Column_6', 'Column_11']
delimiters = ['a','b','c','d']
#inner_dict = dict.fromkeys(delimiters,[0,0])
delim_dict = dict.fromkeys(li1 ,None)
for k,v in delim_dict.items():
    delim_dict[k] = {}
    for delim in delimiters:
        delim_dict[k][delim]=[0,0]

But, how can i achieve the same result with deep copy or is there any other efficient way?

Note: I tried following this link: Deep copy of a dict in python No luck.

question from:https://stackoverflow.com/questions/66066312/why-doesnt-deepcopy-work-on-this-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're using the same list object as all inner_dict values, and deepcopy respects that and keeps it that way. Which you clearly don't want. So don't do that in the first place. Do inner_dict = {d: [0, 0] for d in delimiters} instead.

As the fromkeys documentation says:

All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...