繁体   English   中英

在 Python 中的值是列表的字典中添加键

[英]Adding a key to a dictionary where the values are lists In Python

我想将变量键作为键添加到字典中,并将值添加到列表中。 这是解决这个问题的正确方法吗?

dict = {}
key = 'hold'
value = 'holdtwo'
value_two = 'holdthree'
dict[key].append(value)
dict[key].append(value_two)

您可以使用 dedfaultdict 来实现这一点

from collections import defaultdict

dictionary = defaultdict(list)
key = 'hold'
value = 'holdtwo'
value_two = 'holdthree'
dictionary[key].append(value)
dictionary[key].append(value_two)

不要使用使用关键字作为变量!

dict = {} # dict is a keyword

你问它的问题!

dict1 = {}
dict1['key'] = ['hold','hold2','hold3']
dict1['key'].append('hold4')

或更广泛和更大的保持东西的变化(示例):

dict1 = {}
keys = ['key1', 'key2', 'key3']

for key1 in keys:
    dict1[key1] = []

vals = [1,2,3,4,5,6,7,8,9,10]  #Just some values to store in the dicts

iKey = 1  #iKey is just an offset to show the differences between keys
for key2 in dict1:
    iKey = iKey + 5
    for val in vals:
        dict[key2].append(iKey*val)

大量的选项。

解决了!

如果我想放入一个具有空列表的新密钥,我使用:

new_key = 'something'
dict[new_key] = []

如果我想向现有键的列表添加一个值:

value = 'something else'
dict[new_key].append(value)

这似乎与变量作为键一起工作得很好。

暂无
暂无

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

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