字典中有多少项在Python中共享相同的值 [英] How many items in a dictionary share the same value in Python

查看:231
本文介绍了字典中有多少项在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()))]

这篇关于字典中有多少项在Python中共享相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆