Home > Back-end >  how to add value to a python dictionary list
how to add value to a python dictionary list

Time:07-20

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

CodePudding user response:

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.

CodePudding user response:

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'])  
  • Related