0

How do I add the value two only to the "AF3" list?

x = dict.fromkeys(['AF3', 'AF4', 'AF7', 'AF8', 'AFz', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'CP1', 'CP2', 'CP3', 'CP4',
                   'CP5', 'CP6', 'Cz', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'FC1', 'FC2', 'FC3', 'FC4', 'FC5',
                   'FC6', 'FCz', 'FT10', 'FT7', 'FT8', 'FT9', 'Fp1', 'Fp2', 'Fz', 'O1', 'O2', 'Oz', 'P1', 'P2', 'P3', 'P4',
                   'P5', 'P6', 'P7', 'P8', 'PO3', 'PO4', 'PO7', 'PO8', 'POz', 'T7', 'T8', 'TP10', 'TP7', 'TP8', 'TP9','PD'], [])

x['AF3'].append(2)

dictionary

ricciuto99
  • 21
  • 3
  • List is *mutable* type, so using it as default value you just assign reference to same list to each key, that's why modifying value of any key affects value of every key, because it's the same list. – Olvin Roght Jul 19 '22 at 15:54
  • 2
    All the values point to the same list so you have to create it with a dict comprehension or else – Dani Mesejo Jul 19 '22 at 15:54
  • Check this: https://stackoverflow.com/questions/52068188/how-to-build-a-dict-which-all-values-are-independent-instances-of-in-python – Cuartero Jul 19 '22 at 15:56

2 Answers2

0

When creating the dict, you assign each keys to the same list. Then, if you append to any of the keys, since each key points to the same list, it will append the element to each key.

What you want is a different list for each keys. For example, you could create your dict from a dict-comprehension:

keys = ["AF3", "OTHERKEYS..."]
x = {key: [] for key in keys}
x["AF3"].append(2)  # this will only append to AF3 only.
fgoudra
  • 751
  • 8
  • 23
0

As mentioned all the values point to the same list during the dictionary creation. I would probably use fgoudra's answer but in case you don't have control over how x gets made you can override it like this:

x['AF3'] = []  
x['AF3'].append(2)
print (x['AF3'])  
sniperd
  • 5,124
  • 6
  • 28
  • 44