python - 在字典列表中查找最常出现的字典的最佳方法
问题描述
我有一个字典列表,其中每个字典都有键“形状”和“颜色”。例如:
info = [
{'shape': 'pentagon', 'colour': 'red'},
{'shape': 'rectangle', 'colour': 'white'},
# etc etc
]
我需要找到最常见的形状/颜色组合。我决定通过在列表中查找最常出现的字典来做到这一点。我已经将我的方法缩减为:
frequency = defaultdict(int)
for i in info:
hashed = json.dumps(i) # Get dictionary, turn into string to store as key in frequency dict
frequency[hashed] += 1
most_common = max(frequency, key = frequency.get) # Get most common key and unhash it back into dict
print(json.loads(most_common))
我对 python 有点陌生,我总是最终发现一些 1-2 行函数最终会做我想做的事情。我想知道在这种情况下是否存在更快的方法?也许这最终可以帮助另一个初学者,因为经过多年的谷歌搜索,我找不到任何东西。
解决方案
如果列表中的项目具有一致的键,则更好的选择是使用 anamedtuple
代替 adict
例如:
from collections import namedtuple
# Define the named tuple
MyItem = namedtuple("MyItem", "shape colour")
# Create your list of data
info = [
MyItem('pentagon', 'red'),
MyItem('rectangle', 'white'),
# etc etc
]
这提供了许多好处:
# To instantiate
item = MyItem("pentagon", "red")
# or using keyword arguments
item = MyItem(shape="pentagon", colour="red")
# or from your existing dict
item = MyItem(**{'shape': 'pentagon', 'colour': 'red'})
# Accessors
print(item.shape)
print(item.colour)
# Decomposition
shape, colour = item
然而,回到计数匹配项的问题,因为 anamedtuple
是可散列collections.Counter
的,所以计数代码变为:
from collections import Counter
frequency = Counter(info)
# Get the items in the order of most common
frequency.most_common()
享受!
推荐阅读
- hyperledger-fabric - 如果非确定性合约通过共识配额,剩余节点在超级账本结构中的结果不同,会发生什么情况
- azure - 如何通过app service local git deploy成功部署到bot service?
- javascript - 当我将它分成两个文件时,Node.js https 服务器不起作用
- java - 使用maven在Java项目中运行随机顺序测试类
- c# - ASP.NET Core 错误:尝试激活时无法解析服务类型
- html - 如何强制“标题”属性显示,即使是“" 激活(点击)
- javascript - v-img 的 Vuetify 动态高度
- mysql - 在 MySQL 中更新列中的 WHERE 子句与 - OR LOGICAL 运算符结合使用
- azure-data-explorer - 如何使用先前定义/让 externaldata 执行“in”表达式
- amazon-web-services - 将 180 万的 S3 文件夹从私有更改为公共读取失败,没有详细错误