-1

I have a list containing values that should be used as keys for a dictionary. Right now the list to be converted to keys looks like the following:

myList = ["A", "B"]

I am converting this list to be the keys to a dictionary by doing the following:

newDict = dict.fromkeys(myList, {"Min":[], "Max":[], "Avg":[]})

When printing newDict I get the output:

{'A': {'Min': [], 'Max': [], 'Avg': []}, 'B': {'Min': [], 'Max': [], 'Avg': []}}

However, when trying to write to the newDict["B"]["Avg"] list, the value gets added to both the "A" and "B" keys:

Code:

newDict["B"]["Avg"].append(111)

Output:

{'A': {'Min': [], 'Max': [], 'Avg': [111]}, 'B': {'Min': [], 'Max': [], 'Avg': [111]}}

Is there for the appended value to only be added to the intended key?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
acegay27
  • 7
  • 2
  • 2
    Does this answer your question? [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – Tom Karzes Aug 12 '22 at 14:14
  • Both `A` and `B` keys refer to the _same object!_ – Pranav Hosangadi Aug 12 '22 at 14:15
  • This is one of the most commonly asked Python questions. You have multiple references to the same object. See the duplicate answer for a detailed explanation. – Tom Karzes Aug 12 '22 at 14:15

2 Answers2

3

This comes a lot when handling arrays and dicts. What I prefer to do is use list/dict comprehensions to initialize a new object every time.

newDict = {k: {"Min":[], "Max":[], "Avg":[]} for k in myList}

With the initial method, your keys are pointing at the same object with the same id. You may briefly check this with a simple

newDict['A'] is newDict['B'] # True

class names can be camelCase, but not variables. Maybe pep8 will help you further in your journey through python. Thank you.

2

That's because both the keys are given the value {"Min":[], "Max":[], "Avg":[]}, which is the one dict in both case, rather than two identical dicts.

You can verify by calling id on each dict.

[id(v) for v in newDict.values()] # gives [4618156608, 4618156608]

Or as @FlorianAendekerk suggested, with is

newDict["A"] is newDict["B"]  # gives True

You can fix it by creating a new dictionnary for each key for instance with a dict comprehenssion:

newDict = {k: {"Min":[], "Max":[], "Avg":[]} for k in myList}

PS. you should check out PEP8 as variables are not suposed to be camelCase or PascalCase.

ljmc
  • 4,830
  • 2
  • 7
  • 26