问题
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