簡體   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