1

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?

Fatih1923
  • 2,665
  • 3
  • 21
  • 28
  • Use the good ol' dict-comprehensions. – Ashwini Chaudhary Mar 27 '16 at 22:09
  • This should not have been closed. The issue here quite different from the linked answer. The issues is that even though the poster is attempted to add a *copy* in the function call, fundamentally, the same object (or copy) is used for all initial instantiations. You get similar behavior if you pass in a dictionary (all values are the *same* dictionary). – Wyrmwood Apr 13 '22 at 23:38

1 Answers1

0

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.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
  • The former is also going to create a new list object every time, not so useful if we are dealing with huge lists. Correct solution is to assign different object to each key to prevent such mutation. – Ashwini Chaudhary Mar 27 '16 at 22:17
  • This is true, but I think the OP's specific problem is that *every* value in the key was updated. – Akshat Mahajan Mar 27 '16 at 22:20
  • 1
    Right, but the issue is with how they are initializing the dictionary not with `list.extend`. So, `names_in_years = {k: [] for k in years}` will fix the problem here. – Ashwini Chaudhary Mar 27 '16 at 22:24