Question

I have .txt file example this. It's meant to be Name:Money

Muumimamma:3.3
Pikku Myy:1.3
Muumimamma:2.9
Niiskuneiti:2.2
Muumimamma:8.9
Muumipappa:3.9
Niiskuneiti:3.8
Muumipeikko:2.2
Muumimamma:1.3
Niiskuneiti:2.0
Muumipeikko:3.2
Muumimamma:5.0

I want to make dictionary where the name is key and money is value and if there is the more than once in the file the money should be added together. So my final dictionary should be like this:

{'Muumipappa': 3.9, 'Pikku Myy': 1.3, 'Niiskuneiti': 8.0, 'Muumipeikko': 5.4, 'Muumimamma': 21.4}

Thank you!

Was it helpful?

Solution

A collections.Counter sums the way you want:

from collections import Counter

with open('/tmp/myfile.txt') as f:
    d = sum((Counter({k: float(v) for k, v in [line.split(':')]}) for line in f), Counter())

d = dict(d)

Note that a counter instance is already a subclass of dict, so the line d = dict(d) may not really be necessary depending on your use case.

OTHER TIPS

Use defaultdict from collections with float (there is an example with int in the doc)

from collections import defaultdict
import re

d = defaultdict(float)

with open("money.txt", "r") as f:
  for line in f:
    name, money = re.split(":",line[:-1])
    d[name] += float(money)

So we are not allowed to use import. I came up with this idea, what do you think?

testi = open(file, "r")
lista = testi.readlines()
testi.close()
dict = {}
for arvo in lista:
    arvo = arvo.strip()
    type = arvo.split(":")
    if type[0] in dict:
        dict[type[0]] += float(type[1])
    else:
        dict[type[0]] = float(type[1])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top