Jun-29-2021, 04:47 AM
You can treat it like any
dict
. You can read the elements with .keys()
, the count value with .values()
, or both together with .items()
from collections import Counter with open ("prdcs_file.txt", 'r') as pr_host : c = Counter(x.split(',')[1] for x in pr_host.read().splitlines()) print('\n'.join(f"{k}, {v}" for k,v in c.items()))
Output:DV1, 1
PHQ, 4
ATC, 3
DG2, 1
TGP_H, 1
TCP_H, 2
Or if you want them in order by greatest count, you can use most_common()
in place of items()
from collections import Counter with open ("prdcs_file.txt", 'r') as pr_host : c = Counter(x.split(',')[1] for x in pr_host.read().splitlines()) print('\n'.join(f"{k}, {v}" for k,v in c.most_common()))
Output:PHQ, 4
ATC, 3
TCP_H, 2
DV1, 1
DG2, 1
TGP_H, 1