Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)   
like image 847
user3489966 Avatar asked Feb 20 '26 17:02

user3489966


1 Answers

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))
like image 152
Anish Shah Avatar answered Feb 23 '26 05:02

Anish Shah