[英]Python dictionary appending is adding to front of dictionary instead of end
[英]Adding to a dictionary in python instead of appending
我的原始數據是:
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))
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))
這是使用默認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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.