python - How to get number of keys for a nested value in a dictionary?
问题描述
I have a dictionary where keys have the same values.
products = {
1: {1:1, 2:2, 3:3},
2: {1:1, 2:2, 3:3},
3: {1:1, 2:2, 3:3},
4: {1:2, 2:3, 3:4}
}
I'm looking for the fastest method to get their count without going into two for loops to compare them (since I'm working with 10000+ such key, value pairs)
{1:1, 2:2, 3:3}: 3
{1:2, 2:3, 3:4}: 1
The only solutions I could find was using collection.Counter
but since it's a nested dictionary, it doesn't work. I could work with a list instead, but it doesn't really help.
解决方案
Something like?
>>> x = [*products.values()]
>>> {x.count(dct): dct for dct in products.values()}
{3: {1: 1, 2: 2, 3: 3}, 1: {1: 2, 2: 3, 3: 4}}
>>>
推荐阅读
- go - 调用 eq 时出错:Go 模板中的比较类型无效
- r - 按物种、地点和日期绘制的不同直方图
- compiler-construction - LLVM IR 嵌套 phi 指令
- julia - 如何在 julia-0.7 中丢失所有缺失向量的平均值?
- oracle - 从 XMLTYPE 解析多列
- javascript - Javascript 对象 - 将对象数组与一些经典对象合并
- java - 将多个字符串转换为一个
- node.js - 找不到socket.io/socket.io.js
- html - Active Storage 以 HTML 格式输出图像元数据
- lua - Roblox Studio 如何打开和关闭打印