How to filter dictionary keys based on its corresponding values

前端 未结 6 1101
南笙
南笙 2021-01-30 04:50

I have:

dictionary = {\"foo\":12, \"bar\":2, \"jim\":4, \"bob\": 17}

I want to iterate over this dictionary, but over the values instead of the

6条回答
  •  长情又很酷
    2021-01-30 05:48

    I think the best way to do this (considering migration to Python 3) is

    >>> mydict = {'foo': 12, 'bar': 2, 'jim': 4, 'bob': 17}
    >>> [k for k in mydict if mydict[k] > 6]
    ['bob', 'foo']
    

    The criteria for "best" is readability.

    (Disclaimer: my answer is based in Alex Martelli's answer to other question https://stackoverflow.com/a/3744713/556413 and @jamylak's to this question)

提交回复
热议问题