[英]searching dictionary for string and returning other value
尝试搜索我创建的名为location_hw_map的字典时,我希望它能够搜索字符串'testString'中的一个单词,当找到该单词时,它将返回位置。
例如; 使用testString它应该打印出'lounge'的值
我的代码对其进行搜索并找到“ 123456789”,但我似乎无法将其打印为“休息室”!
我敢肯定这是一个简单的解决方案,但是我似乎找不到答案!
马克斯
也将副本放在这里; http://pythonfiddle.com/python-find-string-in-dictionary
#map hardware ID to location
location_hw_map = {'285A9282300F1' : 'outside1',
'123456789' : 'lounge',
'987654321' : 'kitchen'}
testString = "uyrfr-abcdefgh/123456789/foobar"
if any(z in testString for z in location_hw_map):
print "found" #found the HW ID in testString
#neither of the below work!!
#print location_hw_map[testString] #print the location
#print location_hw_map[z]
不用使用any()
来检查测试字符串是否在字典的键中,而是遍历字典的键:
for i in location_hw_map: # Loops through every key in the dictionary
if i in testString: # If the key is in the test string (if "123456789" is in "uyrfr..."
print location_hw_map[i] # Print the value of the key
break # We break out of the loop incase of multiple keys that are in the test string
印刷品:
lounge
# A generator to return key-value pairs from the dict
# whenever the key is in testString.
g = ([k,v] for k,v in location_hw_map.iteritems() if k in testString)
# Grab the first pair.
# k and v will both be None if not found.
k, v = next(g, (None, None))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.