Tef Don
Tef Don

Reputation: 79

Python count a value inside a list of dictionaries

Assume I have this list of dictionaries:

c = [
    {"name": "Tom", "age": 10, "tag": "kid"},
    {"name": "Mark", "age": 35, "tag": "adult" },
    {"name": "Pam", "age": 70, "tag": "very old"},
    {"name": "Neo", "age": 16, "tag": "teenager"},
    {"name": "Anna", "age": 9, "tag": "kid"}
]

I want to write a function that iterates the list c (and returns a dictionary) to get how many times the value of tag occurs in the list of dictionaries. In this case it should return a dictionary like this:

f = {"kid": 2, "adult": 1, "very old": 1, "teenager": 1}

How to achieve this?

Upvotes: 0

Views: 68

Answers (3)

JhonnyB
JhonnyB

Reputation: 41

You can also create an empty dict and loop over the initial dict like this:

tag_counts = dict()

for tag in c:
  if (tag['tag'] in tag_counts) == False:
    tag_counts[tag['tag']] = 1
  else:
    tag_counts[tag['tag']] += 1

Which will give you

{'adult': 1, 'kid': 2, 'teenager': 1, 'very old': 1}

Upvotes: 1

xjcl
xjcl

Reputation: 15309

from collections import Counter
print(Counter(el["tag"] for el in c))
Counter({'kid': 2, 'adult': 1, 'very old': 1, 'teenager': 1})

Counter is a subclass of dict and can be used like a dict

Upvotes: 2

Sreeram TP
Sreeram TP

Reputation: 11917

If you can use pandas, (which is personally think is an overkill for this problem)

import pandas as pd
pd.DataFrame(c).groupby("tag").size().to_dict()

{'adult': 1, 'kid': 2, 'teenager': 1, 'very old': 1}

Upvotes: 1

Related Questions