简体   繁体   English

将文件转换为包含重复项的字典

[英]Converting File to Dictionary Including Duplicates

I want to convert a file of floats into a dictionary which includes any duplicates there may be.我想将一个浮点数文件转换为一个字典,其中包含可能存在的任何重复项。 For example, I have a .txt file f.例如,我有一个 .txt 文件 f。

1.1 1.1 2.2 3.3 5.5 5.5 5.5 1.1 1.1 2.2 3.3 5.5 5.5 5.5

And I want a dictionary that would say我想要一本会说的字典

{1.1: 2, 2.2: 1, 3.3: 1, 5.5: 3} {1.1: 2, 2.2: 1, 3.3: 1, 5.5: 3}

How can I do this???我怎样才能做到这一点???

You can use collections.Counter :您可以使用collections.Counter

from collections import Counter
f = '1.1 1.1 2.2 3.3 5.5 5.5 5.5'
d = dict(Counter([float(x) for x in f.split()]))
print(d)

Output:输出:

{1.1: 2, 2.2: 1, 3.3: 1, 5.5: 3}

You can create dictionary with default zero and add to it for each element in the list:您可以创建默认为零的字典,并为列表中的每个元素添加:

f = "1.1 1.1 2.2 3.3 5.5 5.5 5.5"

d = {k:0 for k in set(f.split())}

for e in d:
   d[e]+=1
   
print(d)

Output输出

{'5.5': 3, '2.2': 1, '3.3': 1, '1.1': 2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM