Ville
Ville

Reputation: 23

Turning Text file to dictionary

I have a text file that has following structure:

mom:2
dad:3
mom:4
dad:2
me:4

And I need to make a dictionary that would display each name only once, but adding the numeric values together. In this case it would look like this:

{dad':5, 'me':4, 'mom':6}

How I should approach this problem? I've tried

d = {}
  try:
    file = open(file.txt, "r")
    for line in file:
      (a, b) = line.split(":")
      d[a] = float(b)
  except IOError:
    print()

but i haven't found a way to count up the values.

Upvotes: 1

Views: 88

Answers (1)

Vidhya G
Vidhya G

Reputation: 2320

with open('file.txt', 'r') as f:                                                        
    fp = f.readlines()              

t = [l.strip().split(':') for l in fp if l != '\n']                                                                                                                   
d = {}                                                                                 
for l in t:                                                                          
    d[l[0]] = d.setdefault(l[0], 0) + int(l[1]) 

Upvotes: 1

Related Questions