gpt4 book ai didi

python - 在 python 中添加到字典而不是追加

转载 作者:行者123 更新时间:2023-11-28 17:42:07 25 4
gpt4 key购买 nike

我的原始数据是:

abc 123
abc 456
def 789
def 101112

我想把它放入字典中,其中第一列是键,第二列是值。在我目前拥有的字典中:

{'abc': ['123', '456'], 'def': ['789', '101112']}

我想将它们添加到原始值,而不是附加值,这样它看起来像:

{'abc': ['579'], 'def': ['101901']}

我当前的代码是:

d = defaultdict(list)
infile = open('test.csv','r')
lines = infile.readlines()[2:-1]
for item in lines:
key, value = [a.strip() for a in item.split(' ')]
d[key].append(value)

最佳答案

d = defaultdict(list)
infile = open('test.csv','r')
lines = infile.readlines()[2:-1]
for item in lines:
key, value = [a.strip() for a in item.split(' ')]
if key in d:
d[key][0] = str(int(d[key][0]) + value)
else:
d[key].append(str(value))

关于python - 在 python 中添加到字典而不是追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22815577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com