简体   繁体   English

在python字典中查找特定列表

[英]finding particular lists in a dictionary in python

I have a dictionary like this 我有这样的字典

my_d = {"a": [1, 2, 2, 5, 2],
        "b": [2, 1, 2, 4, 5],
        "c": [7, 2, 2, 6, 2], 
        "d": [7, 2, 2, 2, 2]}

I am looking for the keys whose dictionary values contain 2 more than twice. 我正在寻找其字典值包含两次以上的2键。 In the example, that would be "a","c","d" . 在示例中,将为"a","c","d"

You can use count function in a list comprehension : 您可以在列表理解中使用count函数:

>>> my_d = {"a":[1,2,2,5,2],"b":[2,1,2,4,5],"c":[7,2,2,6,2], "d":[7,2,2,2,2]}
>>> [i for i,j in my_d.items() if j.count(2)>2]
['a', 'c', 'd']

my_d.items() give you the list of the items of your dictionary . my_d.items()提供您字典中各项的列表。

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

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