Beginner
Beginner

Reputation: 147

count the matching value of dictionary value in list and take the final total count of each dictionary matching

I would like to loop the list of dictionaries and match the .values() for each .keys() with a specified string.

For example,

a = [[{'test': 'find', 'another':'trying'}],
[{'test': 'find'},
{'test': 'find'}]]

if .values() == "find"

Here is will count 1 ~ total number of "find". Lastly, print the final count of each list.

It will take all the .values() values which have "find" then count the occurrences and then print it.

My code:

count = 0
for x in a:
    for xx in x:
        if xx["test"] == "find":
            count += 1
    print(count)

Current output:

1 3

My expected output:

1 2

Explanations:

List[List[Dict]]

when use for x in list, it will loop the list within the list. So we have List[Dict]

The example, contain 2 lists within a list. The index is 0 and 1. Index 0 contains only 1 "find" so the count will become 1. Index 1 contains 2 "find", so it will take 1 and 2 as count but I want to get the max value of it which is 2. ** if it have 5 in Index 1 then the count will be 1 ~5, so 5 is taken for my max count***

Is there a way to do this?

Latest problem:

Upvotes: 0

Views: 1142

Answers (2)

vash_the_stampede
vash_the_stampede

Reputation: 4606

Using list comprehension with formatted print and .count()

lst = [[j['test'] for j in i] for i in a]
print('{} {}'.format(lst[0].count('find'), lst[1].count('find')))
# 1 2

Upvotes: 1

user2390182
user2390182

Reputation: 73460

Reset the count for each sublist:

max_count = 0  # initialize max here
for x in a:
    count = 0   # reset count here!
    for xx in x:
        if xx["test"] == "find":
            count += 1
    if count > max_count:
        max_count = count
    print(count)
print(max_count)

Or shorter:

max_count = max(sum(xx['test'] == 'find' for xx in x) for x in a)

Upvotes: 1

Related Questions