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?