Home > Blockchain >  how to count how often a particular key appers in a dict python
how to count how often a particular key appers in a dict python

Time:01-20

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

cnt = 0

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

print(cnt)

  • Related