Jim*_*myK 224 python dictionary find
我在python中有以下字典:
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来查找此词典中是否存在诸如"一个"或"两个"的值.
例如,如果我想知道索引"1"是否存在,我只需要键入:
"1" in d
Run Code Online (Sandbox Code Playgroud)
然后python会告诉我这是真还是假,但我需要做同样的事情,除了找到一个值是否存在.
mac*_*mac 341
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True
Run Code Online (Sandbox Code Playgroud)
出于好奇,一些比较时间:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
编辑:如果你想知道为什么......原因是上面的每一个都返回一个不同类型的对象,它可能适合或不适合查找操作:
>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>
Run Code Online (Sandbox Code Playgroud)
EDIT2:根据评论中的要求......
>>> 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]
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 28
您可以使用
"one" in d.itervalues()
Run Code Online (Sandbox Code Playgroud)
测试"one"你的词典中是否包含值.
Sha*_*eem 22
Python字典有(关键)功能
>>> d.get(key)
Run Code Online (Sandbox Code Playgroud)
例如,
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
none
Run Code Online (Sandbox Code Playgroud)
如果您的密钥不存在,将返回none值.
foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return none if key doesn't exist
Run Code Online (Sandbox Code Playgroud)
与小于3.0且大于5.0的版本相关的内容..
sou*_*eck 10
使用字典视图:
if x in d.viewvalues():
dosomething()..
Run Code Online (Sandbox Code Playgroud)
小智 5
Different types to check the values exists
d = {"key1":"value1", "key2":"value2"}
"value10" in d.values()
>> False
Run Code Online (Sandbox Code Playgroud)
What if list of values
test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6']}
"value4" in [x for v in test.values() for x in v]
>>True
Run Code Online (Sandbox Code Playgroud)
What if list of values with string values
test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6'], 'key5':'value10'}
values = test.values()
"value10" in [x for v in test.values() for x in v] or 'value10' in values
>>True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
430131 次 |
| 最近记录: |