Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum similar items
#2
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
tester_V likes this post
Reply


Messages In This Thread
Sum similar items - by tester_V - Jun-29-2021, 04:09 AM
RE: Sum similar items - by bowlofred - Jun-29-2021, 04:47 AM
RE: Sum similar items - by deanhystad - Jun-29-2021, 04:51 AM
RE: Sum similar items - by tester_V - Jun-29-2021, 06:58 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python: if 'X' in 'Y' but with two similar strings as 'X' DreamingInsanity 6 5,293 Feb-01-2019, 01:28 PM
Last Post: buran
  Similar to Poker bluekade5050 1 42,824 Nov-14-2018, 04:46 PM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020