Count the Number of Occurrences of a Certain Value in a Dictionary in Python

count the number of occurrences of a certain value in a dictionary in python?

As mentioned in THIS ANSWER using operator.countOf() is the way to go but you can also use a generator within sum() function as following:

sum(value == 0 for value in D.values())
# Or the following which is more optimized
sum(1 for v in D.values() if v == 0)

Or as a slightly more optimized and functional approach you can use map function by passing the __eq__ method of the integer as the constructor function.

sum(map((0).__eq__, D.values()))

Benchmark:

In [15]: D = dict(zip(range(1000), range(1000)))

In [16]: %timeit sum(map((0).__eq__, D.values()))
49.6 µs ± 770 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [17]: %timeit sum(v==0 for v in D.values())
60.9 µs ± 669 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [18]: %timeit sum(1 for v in D.values() if v == 0)
30.2 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [19]: %timeit countOf(D.values(), 0)
16.8 µs ± 74.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Note that although using map function in this case may be more optimized, but in order to have a more comprehensive and general idea about the two approaches you should run the benchmark for relatively large datasets as well. Then, you can use the most proper approach based on the structure and amount of data you have.

How do you count the occurrences of a value in a dictionary?

Your solution is on the right track! You have the right idea in terms of increasing the counter if the value at the current index of the loop is equal to "online" however you are not actually increasing the count, you are just adding to it though that expression is not actually saved to the variable.

count + 1

should be:

count = count + 1

The reason for this is so that you can make count equal to itself (its current counter value), and +1 to increase the counter.

To simplify this further, you can just write count += 1 which does the same thing.

Final Code:

statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online"
}

def online_count(dict_a):
count = 0
for i in dict_a:
if dict_a[i] == "online":
count += 1
return count

count number of occurrences in list by dict with key and value

You need them all to be at least as large. That means that you have to complete the loop before you can return success. Any failure means that you can return immediately.

for k, v in expected.items():
if results.count(k) < v:
return False

return True

Or, use the all function to put this into a single line:

return all(results.count(k) >= v for k, v in expected.items() )

Counting the occurrences of a value in a column and storing to dictionary

You are almost there. If you have a dataframe

df = pd.DataFrame({'Name':['Ann','Bob','Ann','Bob','Ann',], 'Age':[23,34,45,56,12]})

then running this:

df.groupby('Name').count().to_dict(orient='dict')['Age']

produces

{'Ann': 3, 'Bob': 2}

How can I count occurrences of values in a list of dicts?

Given the result you've got so far...

>>> result = {'LARCENY' : 3, 'BURGLARY' : 2, 'ROBBERY - STREET' : 3}
>>> result = [{k:v} for k,v in result.items()]
>>> result
[{'BURGLARY': 2}, {'LARCENY': 3}, {'ROBBERY - STREET': 3}]

How do I find if a value exists in a dictionary?

You can do this as follows:

c=0
for i in d.values():
if i=='Fred':
c+=1
print(c)

Python counting occurrence of values in dictionary

You don't need to keep duplicated copies of the same items in a list. Use a collections.Counter object to keep count of each object reading straight from your CSV reader/file, keying each counter on the corresponding date in a collections.defaultdict:

from collections import Counter, defaultdict

d = defaultdict(Counter)

for date, country in csv_reader:
d[date][country] += 1

You can then use the most_common method of the Counter objects to get the countries with the most occurrence at each date:

for date, counter in d.items():
print(date, counter.most_common(3))


Related Topics



Leave a reply



Submit