首页 > 解决方案 > 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.

标签: pythondictionary

解决方案


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

推荐阅读