python字典如何判断是否存在某个值,如何检查字典中是否存在值(python)

I have the following dictionary in python:

d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}

I need a way to find if a value such as "one" or "two" exists in this dictionary.

For example, if I wanted to know if the index "1" existed I would simply have to type:

"1" in d

And then python would tell me if that is true or false, however I need to do that same exact thing except to find if a value exists.

解决方案>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}

>>> 'one' in d.values()

True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()

[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]

>>> T(lambda : 'one' in d.values()).repeat()

[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]

>>> T(lambda : 'one' in d.viewvalues()).repeat()

[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())

>>> type(d.values())

>>> type(d.itervalues())

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()

[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]

>>> T(lambda : 'four' in d.values()).repeat()

[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]

>>> T(lambda : 'four' in d.viewvalues()).repeat()

[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值