Python dict.fromkeys() generates copies of list() instead of a new one [duplicate]

纵然是瞬间 提交于 2019-12-25 16:04:29

问题


I want to generate a dictionary using dict.fromkeys() method. I have a years list and i want to assign values them a list object. The problem is that dict.fromkeys() generates copies of list. So, when i update elements of list, it updates all of copies.

>>> years=["1","2","3"]
>>> names=["a","b","c"]
>>> blank=[]
>>> names_in_years=dict.fromkeys(years,blank.copy())
>>> names_in_years
{'2': [], '4': [], '3': [], '1': []}
>>> names_in_years["2"].extend(names)
>>> names_in_years
{'2': ['a', 'b', 'c'], '4': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '1': ['a', 'b', 'c']}

I want to update dictionary objects, individually.the result is below that i want:

{'2': ['a', 'b', 'c'], '4': [], '3': [], '1': []}

Is there a method to do this in a single line?


回答1:


Just do

names_in_years["2"] = names_in_years["2"] + names

instead of the clunky

names_in_years["2"].extend(names)

The former assigns the new value to the old one, the latter mutates the returned value in place. In dealing with updating key values, assignment is usually safer and more foolproof than in-place mutation.



来源:https://stackoverflow.com/questions/36253182/python-dict-fromkeys-generates-copies-of-list-instead-of-a-new-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!