简体   繁体   中英

How to format this dictionary in a specific way

I'm making a program that counts the occurrences of each string in a file so I wrote this

f = open('strings.txt', 'r')
content = f.read()
mystr = list(content)
data = {k: mystr.count(k) for k in mystr}
print(data)

How do I print the output in a format like this for example

 whitespace = 286
 "e" = 204
 "n" = 164
 "i" = 156
 "a" = 147

use python string format :

for key, value in data.items():
    print("{}={}".format(key, value))

However your solution is not efficient and collections.Counter already solve this problem with an more efficient way:

from collections import Counter
words = ['x','y','z','x','x','x','y', 'z']
print(Counter(words))

# Counter({'x': 4, 'y': 2, 'z': 2})

for sorting the results you can use sorted like this:

x = Counter(words)
sorted(x.items(), key=lambda i: i[1])

or

sorted(x.items(), key=lambda i: i[1], reverse=True)  # to sort in ascending order

[f'{i}={j}' for i,j in data.items()]

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