Reputation: 2319
Suppose I have a list of dictionaries that all share the keys color
and object
:
inpt = [{'object':'square', 'color':'red', 'size':'big'},
{'object':'square', 'color':'red', 'coord':(0,0)},
{'object':'square', 'color':'red'},
{'object':'triangle', 'color':'blue', 'adj':'beautiful'},
{'object':'triangle', 'color':'blue', 'attr':'none'}]
Here I only care about object
and color
. I'd like to count the number of red squares and blue triangles for instance. This means finding the number of times {'object':'square', 'color':'red'}
and {'object':'triangle', 'color':'blue'}
occurred. In other words, I need to find the number of commonalities in the key-value pairs in a list of dictionaries like this.
The end result could for example be something like this:
{('square', 'red'): 3, ('triangle', 'blue'):2}
What is an easy way to do this?
Upvotes: 3
Views: 1493
Reputation: 1121486
Just use a collections.Counter()
object, feeding it tuples of the values:
from collections import Counter
result = Counter((d['object'], d['color']) for d in inpt)
This gives you a dictionary subclass with (object, color)
keys. You could get a list of tuples, in descending count order, using the Counter.most_common()
method:
result = result.most_common()
Demo:
>>> from collections import Counter
>>> inpt = [{'object':'square', 'color':'red', 'size':'big'},
... {'object':'square', 'color':'red', 'coord':(0,0)},
... {'object':'square', 'color':'red'},
... {'object':'triangle', 'color':'blue', 'adj':'beautiful'},
... {'object':'triangle', 'color':'blue', 'attr':'none'}]
>>> Counter((d['object'], d['color']) for d in inpt)
Counter({('square', 'red'): 3, ('triangle', 'blue'): 2})
>>> _.most_common()
[(('square', 'red'), 3), (('triangle', 'blue'), 2)]
Upvotes: 6