how to count how often a particular key appers in a dict python

Question:

So I have a dict like that:

{
"channel_list" : [
        {
            "channel_index" : 0,
            "channel_sth" : "A",
        },
        {
            "channel_index" : 1,
            "channel_sth" : "B",
        }]
}

and I would like to count how often the "channel_index" appers in that dict.
How to do it?

Asked By: huschhusch

||

Answers:

The simple answer is to create a variable that counts the amount of "channel_index" in the list and then make a for loop that increments 1 to the variable everytime the name is found, like this:

channel_index_count = 0

for channel in example_dict['channel_list']:
    if channel.get('channel_index'): // if 'channel_index' exists
        channel_index_count += 1

print(channel_index_count)

There are definitely more optimal ways of doing this but this is the easiest

Answered By: Levi Barros

you could use the sum() function with a generator expression:

my_dict = {
"channel_list" : [
        {
            "channel_index" : 0,
            "channel_sth" : "A",
        },
        {
            "channel_index" : 1,
            "channel_sth" : "B",
        }]
}
def count_keys(my_dict, key):
    count = sum(key in channel for channel in my_dict["channel_list"])
    return count

count_keys(my_dict, "channel_index")

output :

2
Answered By: saif amdouni
cnt = 0

for ls in dc.values():
    cnt += len([d for d in ls if 'channel_index' in d.keys()])

print(cnt)

Answered By: Jacob Kearney

d1 = eval(input())

def dict_keys_counts(d1):
    list1 = []
    for i in range(0,len(d1["channel_list"])):
        for j in d1["channel_list"][i]:
            list1.append(j)
    list2 = []
    for k in list1:
        if k not in list2:
            list2.append(k)
            print(k,list1.count(k))

dict_keys_counts(d1)
Answered By: Vishal Nagare
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.