python - 计算字典列表中的公共(public)键值对

标签 python dictionary

假设我有一个字典列表,它们都共享键 colorobject:

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'}]

这里我只关心objectcolor。例如,我想计算红色正方形和蓝色三角形的数量。这意味着找到 {'object':'square', 'color':'red'}{'object':'triangle', 'color':'blue 的次数'} 发生。换句话说,我需要在这样的字典列表中找到键值对中的共性数。

最终结果可能是这样的:

{('square', 'red'): 3, ('triangle', 'blue'):2}

有什么简单的方法可以做到这一点?

最佳答案

只需使用 collections.Counter() object ,为它提供值的元组:

from collections import Counter

result = Counter((d['object'], d['color']) for d in inpt)

这为您提供了一个带有 (object, color) 键的字典子类。您可以使用 Counter.most_common() method 以降序排列的方式获取元组列表。 :

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)]

关于python - 计算字典列表中的公共(public)键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246056/

相关文章:

java - 在 Struts2 中访问多键映射

python-3.x - 将 dict 标量转换为 Pandas DataFrame

python - 在 OSX 上安装 PyLucene JCC 时出错

python - 关于Python中的序列类型

带有嵌套列表的 Python 字典键到 pandas DataFrame

C# 将字符串转换为字典

python - 如何制作一个字典,通过 fifo 过程给出输出

python - 在 python 中的 xml 或 html 文件的标签之间获取数据的简单方法?

python - 遍历一个文本文件并为每一行 python 编写一个新的文本文件

python - 索引超出范围 - Python 中的快速排序