How to count the number of occurrences of dictionary keys

I am new to python. How to count the number of occurrences of dictionary keys?

I just want to know different numbers aboout emotion. The data is attached
best wishes

Just want to count the number of emotions corresponding to different emotions, such as how many times sadness appears in the dev dataset? Excuse me, thank you

Hey Aiden,

Is there anything you had written before so we can start from there?

Start by describing how you would count the number of occurrences,
using pencil and paper. What would you do?

Now think about how you would explain it to a five year old. What would
you tell them to do? Write out your instructions in the most clear way
that you can.

Imagine that you are writing instructions for this guy:

That is what programming is like.

But it always starts with working out how you would solve the problem
by hand, then writing some code. So how would you solve the problem?

Dear TobiasHt:

Thank you for your reply.
I only know how to print the value corresponding to a specific key.
But when I count the dev dataset, I don’t need to care about which conversation it comes from, so the second key value can take a random value. I only care about the number of emotion statistics corresponding to emotion in the dev dataset. Could you please help me to fix this issue?
Thanks. This is attached the original data

config[‘dev’][‘random value’][‘Emotion’]


import yaml

from collections import Counter

config = yaml.load(open(’…/content/drive/MyDrive/mfcc_preprocess/melddatasets.yaml’, ‘r’, encoding=‘utf-8’).read())

emotion = config[‘dev’][‘dia0_utt0’][‘Emotion’]


I feel like I’ve not understood what your’e asking. However, there are two ways of solving this problem. You either have to explain your issue until someone understands it and helps you write the code,
OR, you can take time and take a simple python course to learn the basics which you’ll apply in solving this problem. It might be a book, crash course or YouTube tutorial, whatever you feel comfortable with.

Personally I’d go with the second option cause then you’ll grow your skills as a developer.

Dear TobiasHT:

I am very grateful for your help and suggestions. Last hour, I successed in fixing this issue.

best wishes

1 Like

One way to count ‘Emotions’ (assuming that you have pyyaml installed):

import yaml
from collections import Counter

with open('datasets.yaml', 'r') as f:
    data = yaml.safe_load(f)

count = Counter(nested['Emotion'] for record in data.values() for nested in record.values())

On dataset provided count will be:

Counter({'neutral': 6435, 'joy': 2308, 'surprise': 1636, 'anger': 1607, 'sadness': 1002, 'disgust': 361, 'fear': 358})