Reputation: 17
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?
Upvotes: 0
Views: 53
Reputation: 1
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)
Upvotes: 0
Reputation: 156
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
Upvotes: 1
Reputation: 14
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
Upvotes: 0