简体   繁体   中英

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.

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}

How can I do this???

You can use 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}

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.

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