Python-有没有一种方法可以将多个值附加到一个键上?

问题描述 投票:0回答:5

我有一个数字列表,每个数字都有值。我想要做的是检查字典中是否已经存在该数字,如果存在,请将值附加到特定键的值列表中。

示例

0  
a   

2
b

3
c

0
d

7
e

我想要实现的是在字典中填充数字,其中数字是键,字母是值。但是,如果再次出现数字0,我想取第二个0的值并将其附加到我的值列表中。

基本上结果是

 "0" : [a,d]
 "2" : [b]
 "3" : [c]
 "7" : [e]

现在正在执行以下操作:

num_letter_dict = {}
num = ['0', '2', '3', '0','7']
letters = ['a', 'b', 'c', 'd','e']

for line in num:
    if line in num_letter_dict:
        num_letter_dict[line].append(letters)
    else:
        num_letter_dict[line] = [letters]

    print(num_letter_dict)

这是我得到的结果

{'0': [['a', 'b', 'c', 'd', 'e']]}
{'0': [['a', 'b', 'c', 'd', 'e']], '2': [['a', 'b', 'c', 'd', 'e']]}
{'0': [['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']], '2': [['a', 'b', 'c', 'd', 'e']]}
{'0': [['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']], '2': [['a', 'b', 'c', 'd', 'e']], '3': [['a', 'b', 'c', 'd', 'e']]}
{'0': [['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']], '2': [['a', 'b', 'c', 'd', 'e']], '3': [['a', 'b', 'c', 'd', 'e']], '7': [['a', 'b', 'c', 'd', 'e']]}
python dictionary key-value
5个回答
0
投票

您要附加letters,它本身就是完整列表。而是要在letter中附加与要在num列表中查看的键的索引相对应的元素。

for idx, line in enumerate(num):
    if line in num_letter_dict:
        num_letter_dict[line].append(letters[idx]) # append the element
    else:
        num_letter_dict[line] = [letters[idx]]

结果:

>>> print(num_letter_dict)
{'0': ['a', 'c'], '2': ['b'], '3': ['d'], '7': ['e']}

0
投票

您只需要将单个字母添加到字典内的相关列表中,而不是整个字母列表。 zip函数将循环显示来自两个输入列表的相应值,如下所示:

num_letter_dict = {}
num = ['0', '2', '3', '0','7']
letters = ['a', 'b', 'c', 'd','e']

for n, letter in zip(num, letters):
    if n not in num_letter_dict:
        num_letter_dict[n] = []
    num_letter_dict[n].append(letter)
print(num_letter_dict)

给予:

{'0': ['a', 'c'], '3': ['d'], '7': ['e'], '2': ['b']}

0
投票

我认为这可以帮助您。

num_letter_dict = {}
num = ['0', '2', '0', '3','7']
letters = ['a', 'b', 'c', 'd','e']

for value, line in zip(letters,num):
    if line in num_letter_dict:
        num_letter_dict[line].append(value) # append the element
    else:
        num_letter_dict[line] = [value]

0
投票

尝试下面的代码,我已经修改了for循环并使用了extend

for i, letter in zip(num, letters):
    if i not in num_letter_dict:
        num_letter_dict[i] = []
    num_letter_dict[i].extend(letter) #change over here
print(num_letter_dict)

0
投票

啊,昨天我不得不处理同样的问题。虽然其他提交的答案可以使用,但我可以推荐defaultdict from the Collections module吗?

defaultdict

[我喜欢这种方法,因为它允许from collections import defaultdict num = ['0', '2', '3', '0','7'] letters = ['a', 'b', 'c', 'd','e'] num_letter_dict = defaultdict(list) for n, letter in zip(num, letters): num_letter_dict[n].append(letter) print(num_letter_dict) 类在内部进行列表的构造,而不是使用if语句混淆自己的源代码。

您可以在IDEOne上测试执行此解决方案:defaultdict

© www.soinside.com 2019 - 2024. All rights reserved.