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!
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)
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.
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])
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.