字典中有多少项在Python中共享相同的值
问题描述:
有没有办法查看字典中有多少项目在Python中共享相同的值?
Is there a way to see how many items in a dictionary share the same value in Python?
假设我有一个字典,如:
Let's say that I have a dictionary like:
{"a": 600, "b": 75, "c": 75, "d": 90}
我想得到一个结果字典,如:
I'd like to get a resulting dictionary like:
{600: 1, 75: 2, 90: 1}
我的第一个天真的尝试将是使用一个嵌套的for循环和每个值,然后我将再次迭代字典。有没有更好的方法来做到这一点?
My first naive attempt would be to just use a nested-for loop and for each value then I would iterate over the dictionary again. Is there a better way to do this?
答
你可以使用itertools.groupby这个。 b
You could use itertools.groupby for this.
import itertools
x = {"a": 600, "b": 75, "c": 75, "d": 90}
[(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]