Skip to content Skip to sidebar Skip to footer

Python Dict.fromkeys() Generates Copies Of List() Instead Of A New One

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 cop

Solution 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.

Post a Comment for "Python Dict.fromkeys() Generates Copies Of List() Instead Of A New One"