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?
CodePudding user response:
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]
CodePudding user response:
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