Tiger1
Tiger1

Reputation: 1377

Python:Counting the number of dictionaries in which a key occur in a list of dictionaries

Here is my dictionary list:

dict_list=[{'red':3, 'orange':4}, {'blue':1, 'red':2},
   {'brown':4, 'orange':7}, {'blue':4, 'pink':10}]

My goal is to get the count of dictionaries in which a key occur, and output a list of dictionaries with the count as values.

My attempt:
new_list=[]
count=0
new_dict={}
for x in dict_list:
    for k,v in x.iteritems():
        if k in x.values():
            count+=1
            new_dict={k:count for k in x.iteritems()}
    new_list.append(new_dict)

My result:
[{}, {}, {}, {}]

Desired result:

[{'red':2, 'orange':2}, {'blue':2, 'red':2},
   {'brown':1, 'orange':2}, {'blue':2, 'pink':1}]

Thanks for your suggestions.

Upvotes: 0

Views: 83

Answers (1)

tobias_k
tobias_k

Reputation: 82889

Try this (Python 2.6):

counts = collections.defaultdict(int)
for d in dict_list:
    for c in d:
        counts[c] += 1
new_list = [dict((c, counts[c]) for c in d) for d in dict_list]

Or, a bit shorter (Python 2.7+):

counts = collections.Counter()
for d in dict_list:
    counts.update(d.keys())
new_list = [{c: counts[c] for c in d} for d in dict_list]

Output:

[{'orange': 2, 'red': 2}, {'blue': 2, 'red': 2}, 
 {'orange': 2, 'brown': 1}, {'blue': 2, 'pink': 1}]

Upvotes: 1

Related Questions