0

I am trying to add a specific value to a specific key in a dictionary, and I got a list of special keys. I am using a for loop to do this, but the result is adding everything to all the keys in the dictionary

keyList = ['a','b','c']
testdict = dict.fromkeys(keyList,[])
specKey = ['a','c']

for i in specKey:
    t = testdict.get(i)
    t.append(i)
print(testdict)

The result is this

{'a': ['a', 'c'], 'b': ['a', 'c'], 'c': ['a', 'c']}

But I expect the result should be like this:

{'a': ['a'], 'b': [], 'c': ['c']}

Can someone tell me what I did wrong? Thanks!

cwl6
  • 27
  • 6

1 Answers1

1

The line:

dict.fromkeys(keyList, [])

creates the same list which is shared by all keys.

Instead, explicitly create list to each key:

keyList = ['a','b','c']
testdict = { k : list() for k in keyList}
specKey = ['a','c']

for i in specKey:
    testdict[i].append(i)

# {'a': ['a'], 'b': [], 'c': ['c']}
print(testdict)
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22