我有下面的python字典:
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
我需要一种方法来查找这个字典中是否存在诸如“1”或“2”这样的值。
例如,如果我想知道索引“1”是否存在,我只需要输入:
"1" in d
然后python会告诉我这是真还是假,但是我需要做同样的事情,除了找到一个值是否存在。
我有下面的python字典:
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
我需要一种方法来查找这个字典中是否存在诸如“1”或“2”这样的值。
例如,如果我想知道索引“1”是否存在,我只需要输入:
"1" in d
然后python会告诉我这是真还是假,但是我需要做同样的事情,除了找到一个值是否存在。
当前回答
你可以用这个:
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
print("one" in d.values)
或者你可以使用任何函数:
print(any([True for i,j in d1.items() if j == "one"]))
其他回答
Python字典有get(key)函数
>>> d.get(key)
例如,
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
None
如果你的键不存在,那么它将返回None值。
foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return None if key doesn't exist
与版本小于3.0和大于5.0相关的内容。
在Python 3中,您可以使用字典的values()函数。它返回值的视图对象。这又可以传递给iter函数,该函数返回一个迭代器对象。迭代器可以用in检查,像这样,
'one' in iter(d.values())
或者您可以直接使用视图对象,因为它类似于列表
'one' in d.values()
在Python 3中,您可以使用
"one" in d.values()
测试“1”是否在字典的值中。
在Python 2中,它的使用效率更高
"one" in d.itervalues()
代替。
注意,这会触发对字典值的线性扫描,一旦找到就会短路,因此这比检查键是否存在的效率要低得多。
使用字典视图:
if x in d.viewvalues():
dosomething()..
你可以用这个:
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
print("one" in d.values)
或者你可以使用任何函数:
print(any([True for i,j in d1.items() if j == "one"]))