简体   繁体   中英

Adding to a dictionary in python instead of appending

My raw data is:

abc 123
abc 456
def 789
def 101112

I want to put this into a dictionary where the first column is the key and the second column is the value. In the dictionary I currently have:

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

instead of appending the values I want to add them to the original value so that it looks like:

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

My current code is:

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

Here is version using default 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM