简体   繁体   English

当值是python中的列表列表时,如何将值添加到字典中

[英]how to add a value to a dictionary when the value is a list of lists in python

I am trying to build a dictionary, such that for each key the value is a list of lists.我正在尝试构建一个字典,以便每个键的值都是一个列表列表。 There is a loop in my code thats runs on some list of keys, and if the key not in the dictionary, i add the key to the the dictionary with some value.我的代码中有一个循环运行在一些键列表上,如果键不在字典中,我将键添加到字典中,并带有一些值。 I get into truble when the key is in the dictionary- i cannot add to it another list.当密钥在字典中时,我陷入困境 - 我无法向其中添加另一个列表。

here is example for what i tried:这是我尝试过的示例:

dict={}

dict[x]=[[f,g],[y,e,j]...]
# i tried this:
dict[x]+= [l,k,n]

dict[x].append([l,k,n])

#i expected this:

dict[x] = [[f,g],[y,e,j], ... ,[l,k,n]]

This seems to work for me:这似乎对我有用:

a = [1,2,3]
b = [4,5,6]
d = {}
d['ab'] = [a, b]
d['ab'].append([7,8,9])

Note that d['ab'] += [0,0,0] (as an example) does an extend rather than a append .请注意, d['ab'] += [0,0,0] (作为示例)执行的是extend而不是append If you want to use += then you should wrap the value in a list.如果你想使用+=那么你应该把值包装在一个列表中。 eg:例如:

d['ab'] += [[0,0,0]]

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

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