Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value_counts() for values of a dictionary [duplicate]

I'm very familiar with how to return value_counts from a pd.Series. However, how would I get the value counts from values of a dictionary?

Say that I have the following tuples in dictionary L:

L = {1: (13600, 14797),
     2: (14700, 14700),
     3: (14700, 10400),
     4: (14600, 17200),
     5: (13600, 14797),
     6: (14600, 17200),
     7: (14700, 10400),
     8: (14700, 10400),
     9: (12800, 14770)}

How do I get the value_counts from L that would look like:

(14700, 10400) 3
(13600, 14797) 2
(14600, 17200) 2
(14700, 14700) 1
(12800, 14770) 1

This is what I have so far. However, I think the dictionary keys 1-9 are getting in the way because I get the error list object is not callable.

list = [(k, v) for k, v in L.items()] 
S = set(L)
F = {}
for i in list(S):
    F[i] = list.count(i)
like image 684
JAG2024 Avatar asked Jan 31 '26 04:01

JAG2024


2 Answers

Use collections.Counter from the standard library:

Counter(L.values())
like image 74
Mad Physicist Avatar answered Feb 01 '26 21:02

Mad Physicist


Maybe using from collections import Counter is a good idea?

from collections import Counter 
dict(Counter([j for i,j in L.items()]))
like image 41
snowneji Avatar answered Feb 01 '26 20:02

snowneji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!