如果x是此字典中的值,则... Python [英] If x is a value in this dict... Python

查看:41
本文介绍了如果x是此字典中的值,则... Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

d = {1:2, 3:4}
if 4 in d:
    print 'Aha!'

但是我想从值而不是键中读取.用Python的方式可以做到这一点?

but I want to read from the values and not the keys. What's the Pythonic way to do this?

推荐答案

使用 itervalues :

d = {1:2, 3:4}
if 4 in d.itervalues():
    print 'Aha!'

请注意,这将比键查找要慢得多,因为它可能需要检查字典中的所有值.如果您通常需要执行此操作,则可能需要考虑将值存储在 set 中.

Note that this will be much slower than a key lookup because it will potentially require inspecting all values in the dictionary. If you need to perform this operation often you might want to consider storing the values in a set.

这篇关于如果x是此字典中的值,则... Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆