[英]counting common key-value pairs in a list of dictionaries
假设我有一个所有共享键color
和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'}]
在这里我只关心object
和color
。 我想计算一下红色方块和蓝色三角形的数量。 这意味着找到{'object':'square', 'color':'red'}
和{'object':'triangle', 'color':'blue'}
次数。 换句话说,我需要在像这样的字典列表中找到键值对中的共性数。
最终结果可能是这样的:
{('square', 'red'): 3, ('triangle', 'blue'):2}
有什么简单的方法可以做到这一点?
只需使用collections.Counter()
对象 ,为它提供值的元组:
from collections import Counter
result = Counter((d['object'], d['color']) for d in inpt)
这为您提供了一个带有(object, color)
键的字典子类。 您可以使用Counter.most_common()
方法以降序计数顺序获取元组列表:
result = result.most_common()
演示:
>>> 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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.