![](/img/trans.png)
[英]Python: Check if dataframe cell value exists in Dictionary. If exists replace dataframe value with dictionary key
[英]Python: checking if an item is in a dictionary. Key OR value
我正在尝试仅使用一个命令来检查字典的键及其值中是否具有某个值,而不是必须进行两次搜索。 即
'b' in d.keys()
'b' in d.keys() or 'b' in d.values()
使用这些术语在互联网上搜索仅返回关于如何仅搜索键或仅搜索值的说明。
d = {'a':'b'}
d.items() ## this is the closest thing I could find to all the items
'b' in d.items() ## but this returns false
没有单个函数可以执行此操作。 您必须要么做(没有keys()更快):
'b' in d or 'b' in d.values()
或某种形式的项目循环:
for i in d.items():
if 'b' in i:
return True
return False
要么:
any(('b' in i) for i in d.items())
PS。 它还指出了不良的设计。 字典对于键查找很酷,因为它们很快。 如果同时检查键和值,则无论如何都只是在浏览所有存储的项目。 (并且它表明您甚至不确定自己在看哪一边)我建议您检查一下集合和字典的某种组合是否更适合您要执行的操作。
d.items()
的问题在于,它返回一个以元组表示的键/值对的列表,因此'b'
将不在[('a', 'b')]
。
all_items = d.keys() + d.values()
'b' in all_items
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.