Jawad Tariq
Jawad Tariq

Reputation: 355

Given a list of dictionaries, how can I find how many dictionaries each key appears in?

I have a list of dictionaries and every dictionary has the word as key, and the number of times that word appears in a particular document as value. Now I am wondering How can I find how many dictionaries a particular word appears in?

suppose I have a list of following dictionaries:

dict1 = {'Association':5, 'Rule':2, 'Mining':3}
dict2 = {'Rule':4, 'Mining':1}
dict3 = {'Association':4, 'Mining':3}

Result after counting how many dictionaries a word appears in:

result_dict = {'Association':2, 'Rule':2, 'Mining':3}

Upvotes: 0

Views: 120

Answers (2)

Itamar Mushkin
Itamar Mushkin

Reputation: 2905

This can be easily done with dict comprehension.
First, make a list out of your dicts:

dict1 = {'Association':5,'Rule':2,'Mining':3}
dict2 = {'Rule':4,'Mining':1}
dict3 = {'Association':4,'Mining':3}

dicts = [dict1, dict2, dict3]

Then, make a set of all the words in the dictionaries with a union (might be a cleaner way to do this, but this worked):

all_words = set().union(*[d.keys() for d in dicts])

Then, count how many dictionaries each word appears in:

{k: sum([1 for d in dicts if k in d.keys()]) for k in all_words}

This returned the desired output from your example.

Upvotes: 1

EliadL
EliadL

Reputation: 7088

Counter is a dict subclass that can be useful here:

from collections import Counter


dicts = [dict1, dict2, dict3]

key_counters = [Counter(dictionary.keys()) for dictionary in dicts]
start_counter = Counter()

result_dict = sum(key_counters, start_counter)

assert result_dict == {'Association': 2, 'Rule': 2, 'Mining': 3}

Upvotes: 2

Related Questions