简体   繁体   English

如何向python字典列表添加值

[英]how to add value to a python dictionary list

How do I add the value two only to the "AF3" list?如何仅将值 2 添加到“AF3”列表中?

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)

字典

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:例如,您可以从 dict-comprehension 创建您的 dict:

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

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:我可能会使用 fgoudra 的答案,但如果您无法控制x的制作方式,您可以像这样覆盖它:

x['AF3'] = []  
x['AF3'].append(2)
print (x['AF3'])  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM