I have .txt file example this. It's meant to be Name:Money
我有.txt文件示例。它的意思是名称:金钱
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!
谢谢!
3 个解决方案
#1
0
A collections.Counter
sums the way you want:
collections.Counter总结你想要的方式:
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.
请注意,计数器实例已经是dict的子类,因此根据您的使用情况,行d = dict(d)可能不是必需的。
#2
0
Use defaultdict
from collections
with float
(there is an example with int
in the doc)
使用带有float的集合中的defaultdict(在doc中有一个带有int的示例)
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)
#3
0
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])
#1
0
A collections.Counter
sums the way you want:
collections.Counter总结你想要的方式:
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.
请注意,计数器实例已经是dict的子类,因此根据您的使用情况,行d = dict(d)可能不是必需的。
#2
0
Use defaultdict
from collections
with float
(there is an example with int
in the doc)
使用带有float的集合中的defaultdict(在doc中有一个带有int的示例)
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)
#3
0
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])