添加到python中的字典而不是追加

时间:2014-04-02 15:04:02

标签: python dictionary

我的原始数据是:

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)   

3 个答案:

答案 0 :(得分:2)

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))

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这是使用默认python dict的版本:

d = dict()
infile = open('test.csv', 'r')
lines = infile.readlines()[2:-1]
for line in lines:
    k, v = [i.strip() for i in line.split(' ')]
    if k in d:
        d[k] = [str(int(d[k][0]) + int(v))]
    else:
        d[k] = [v]
print d