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?
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)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.