1
# list of dict keys
function_vars = ["x_reserve", "y_reserve", "wx", "wy", "decay_rate"]

# Initialize a dictionary with empty array values
stats = dict.fromkeys(function_vars, [])

for var in function_vars:
  print(var)
  stats[var].append(0)

stats

I initialized a dictionary using function_vars elements as dictionary values. Then I want to create a loop that updates each dictionary key once. However I am getting 5x as many values as I anticipated:

    {'decay_rate': [0, 0, 0, 0, 0],
 'wx': [0, 0, 0, 0, 0],
 'wy': [0, 0, 0, 0, 0],
 'x_reserve': [0, 0, 0, 0, 0],
 'y_reserve': [0, 0, 0, 0, 0]}

but the output should be

    {'decay_rate': [0],
 'wx': [0],
 'wy': [0],
 'x_reserve': [0],
 'y_reserve': [0]}

What is going on with my logic? I am not sure what I am missing and how to fix my (wrong) results

Evan Kim
  • 769
  • 2
  • 8
  • 26
  • 1
    They're all pointing to the same list, and you keep appending 0 to that ever-growing list. Similar to the first [Python gotcha](https://docs.python-guide.org/writing/gotchas/). – jarmod Mar 18 '22 at 15:19
  • 1
    See the note in [the docs](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys): *All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.* For example: `stats = {k:[] for k in function_vars}` – Mark Mar 18 '22 at 15:20

0 Answers0