'Count value in dictionary
I am trying to count the number of times a value is repeated in a dictionary.
Here is my code:
bookLogger = [
{'BookName': 'Noise', 'Author': 'Daniel Kahneman', 'Process': 'Reading' },
{'BookName': 'Hunting Party', 'Author': 'Lucy Foley', 'Process': 'Reading'},
{'BookName': 'Superintelligence', 'Author': 'Nick Bostrom', 'Process': 'Not Reading'}
]
So, I'd want to count 'Reading' for example, so that it prints:
Reading = 2
Not Reading = 1
Solution 1:[1]
Use collections.Counter to automatize the counting, then a simple loop for displaying the result:
from collections import Counter
# using "get" in case a dictionary has a missing key
c = Counter(d.get('Process') for d in bookLogger)
# {'Reading': 2, 'Not Reading': 1}
for k,v in c.items():
print(f'{k} = {v}')
output:
Reading = 2
Not Reading = 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
