Python 计算字典中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14743454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:17:50  来源:igfitidea点击:

Counting values in dictionary

pythondictionary

提问by cloud36

I have a dictionary as follows.

我有一本字典如下。

dictA = { 
    'a' : ('duck','duck','goose'), 
    'b' : ('goose','goose'), 
    'c' : ('duck','duck','duck'), 
    'd' : ('goose'), 
    'e' : ('duck','duck') 
    }

I'm hoping to loop through dictA and output a list that will show me the keys in dictA that have more than one "duck" in value.

我希望遍历 dictA 并输出一个列表,该列表将向我显示 dictA 中具有多个“duck”值的键。

For example, for dictA this function would output the below list.

例如,对于 dictA,此函数将输出以下列表。

list = ['a', 'c', 'e']

I'm sure there is an easy way to do this, but I'm new to Python and this has me stumped.

我确信有一种简单的方法可以做到这一点,但我是 Python 新手,这让我很难过。

回答by Ignacio Vazquez-Abrams

[k for (k, v) in dictA.iteritems() if v.count('duck') > 1]

回答by John La Rooy

I think this is a good way for beginners. Don't call your list list- there is a builtin called list

我认为这是初学者的好方法。不要调用你的列表list- 有一个内置的叫做list

>>> dictA = { 
...     'a' : ('duck','duck','goose'), 
...     'b' : ('goose','goose'), 
...     'c' : ('duck','duck','duck'), 
...     'd' : ('goose'), 
...     'e' : ('duck','duck') 
...     }
>>> my_list = []
>>> for key in dictA:
...     if dictA[key].count('duck') > 1:
...         my_list.append(key)
... 
>>> my_list
['a', 'c', 'e']

Next stage is to use .items()so you don't need to look the value up for each key

下一阶段是使用,.items()因此您无需查找每个键的值

>>> my_list = []
>>> for key, value in dictA.items():
...     if value.count('duck') > 1:
...         my_list.append(key)
... 
>>> my_list
['a', 'c', 'e']

When you understand that, you'll find the list comprehension in Ignacio's answer easier to understand.

当您理解这一点时,您会发现 Ignacio 的答案中的列表理解更容易理解。

回答by Burhan Khalid

Just for the heck of it - here is the other, otherway:

只是为了它 - 这是一种方式:

>>> from collections import Counter
>>> [i for i in dictA if Counter(dictA[i])['duck'] > 1]
['a', 'c', 'e']

Counteris for - you guessed it - counting things.

Counter是为了 - 你猜对了 - 数东西。