简体   繁体   English

在字典中计算值

[英]Counting values in dictionary

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的新手,这让我很难过。

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

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的答案中的列表理解更容易理解。

Just for the heck of it - here is the other, other way: 只是为了它 - 这是另一种, 一种方式:

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

Counter is for - you guessed it - counting things. Counter是为了 - 你猜对了 - 计算东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM