且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字典中是否存在值(python)

更新时间:2022-10-22 22:52:53

 >>> d = {'1':'one','3':'three','2':'two','5':'five','4':'four'} 
>&gt ;> d.values()中的'one'
True

出于好奇,一些比较时间:

 >>> T(lambda:'d'itervalues()中的一个)。repeat()
[0.28107285499572754,0.29107213020324707,0.27941107749938965]
>>> T(λ:d.values()中的one)。repeat()
[0.38303399085998535,0.37257885932922363,0.37096405029296875]
>>> T(lambda:d.viewvalues()中的one)。repeat()
[0.32004380226135254,031716084480285645,03171098232269287]

编辑:如果你想知道为什么...原因是上述每个都返回一种不同类型的对象,这可能或可能不太适合查找操作:

 >>> type(d.viewvalues())
< type'dict_values'>
>>>类型(d.values())
< type'list'>
>>> type(d.itervalues())
< type'dictionary-valueiterator'>

EDIT2:根据评论中的请求...

 >>> T(λ:d.itervalues()中的lambda为four)。repeat()
[0.41178202629089355,0.3959040641784668,0.3970959186553955]
>>> T(λ:d.values()中的four)。repeat()
[0.4631338119506836,0.43541407585144043,0.4359898567199707]
>>> T(lambda:'d'view'()中的'four')。repeat()
[0.43414998054504395,0.4213531017303467,0.41684913635253906]


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 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

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]