0

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
Gaemon
  • 43
  • 3
  • 2
    You are reimplementing [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter). `data = Counter(f.read())` could replace all existing code. Also you colud use [`Counter.most_common()`](https://docs.python.org/3/library/collections.html#collections.Counter.most_common): `print(*(f'"{k}" = {v}' for k, v in data.most_common()), sep="\n")` – Olvin Roght Jan 04 '22 at 11:12
  • Another way is str = json.dumps(data, indent=0,separators=('', ':' )) print(str[2:-2]) – AJITH Jan 04 '22 at 11:20

2 Answers2

0

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
Mojtaba Kamyabi
  • 3,440
  • 3
  • 29
  • 50
  • How do I arrange it in descending order based on their count? – Gaemon Jan 04 '22 at 11:25
  • @Gaemon, if you are using [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter), there's specific method [`Counter.most_common()`](https://docs.python.org/3/library/collections.html#collections.Counter.most_common). If you *(for some reasons)* use regular dict, you need to apply [`sorted()`](https://docs.python.org/3/library/functions.html#sorted) and pass [`itemgetter()`](https://docs.python.org/3/library/operator.html#operator.itemgetter) to `key` argument: `sorted(data.items(), key=itemgetter(1), reverse=True)`. – Olvin Roght Jan 04 '22 at 11:30
  • @Gaemon See my updated answer. – Mojtaba Kamyabi Jan 04 '22 at 11:32
  • @MojtabaKamyabi, do not use `lambda` to retrieve element by index, there's [`operator.itemgetter()`](https://docs.python.org/3/library/operator.html#operator.itemgetter). At all, don't use method with sorting for `Counter`, there's a specific method for this. – Olvin Roght Jan 04 '22 at 11:35
  • @OlvinRoght `operator` needs to be imported. anyway what is the drawback of using lambda in this case? – Mojtaba Kamyabi Jan 04 '22 at 11:41
  • @MojtabaKamyabi, it's significantly slower. You can make some benchmarks. And what's wrong with imports? It's part of std library, not third party module, you already have it, why not to use it? – Olvin Roght Jan 04 '22 at 11:43
  • @OlvinRoght yes it seems [you are right](https://stackoverflow.com/a/17243726/1033510). I changed my answer. – Mojtaba Kamyabi Jan 04 '22 at 12:21
0

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

Abhishek Jain
  • 568
  • 2
  • 4
  • 15
  • to print this you'll need to do `print('\n'.join([f'{i}={j}' for i,j in data.items()]))` – Sujal Singh Jan 04 '22 at 11:19
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Jan 05 '22 at 00:30