How to count values of each key in a list

Question:

I have a list like this:

list1 = [
    {'state': 'active', 'name': 'Name1'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'inactive', 'name': 'Name4'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name2'},
]

I’m going to count how many of each name value I have. Like this:

3 counts for Name1
3 counts for Name2
2 counts for Name3
1 counts for Name4

This is my current code:

from collections import defaultdict
list2 = defaultdict(list)
for i in list1:
    list2[i['name']].append(i['name'])

I thought I can count with this (totally failed attempt obviously):

for x in list2:
    sum(x)

How can I count it?

Asked By: Saeed

||

Answers:

Use Counter

from collections import Counter

counter = Counter(d['name'] for d in list1)
print(*counter.items())

# ('Name1', 3) ('Name2', 3) ('Name3', 2) ('Name4', 1)
Answered By: Guy

Okay, in order to do this you can use counter from collections library, if you implement it code will look something like below:

counts = Counter(item['name'] for item in list1)
for name, count in counts.items():
    print(f"{count} counts for {name}")

To count the occurrences of each name in your list of dictionaries, you can use a defaultdict from the collections module, but instead of using a list as the default factory, you should use int. This way, you can increment the count directly. Here’s how you can modify your code to achieve the desired result:

from collections import defaultdict

list1 = [
    {'state': 'active', 'name': 'Name1'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'inactive', 'name': 'Name4'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name2'},
]

name_counts = defaultdict(int)

for item in list1:
    name_counts[item['name']] += 1

for name, count in name_counts.items():
    print(f"{count} counts for {name}")
Answered By: Vietnamese
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.