简体   繁体   中英

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. In the example, that would be "a","c","d" .

You can use count function in a list comprehension :

>>> 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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