在字典中搜索字符串并返回其他值

2024-04-26 00:06:36 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试搜索我创建的名为location\uhw\u map的字典,我希望它能够在字符串“testString”中搜索其中一个单词,找到后将返回位置。你知道吗

例如,使用testString它应该打印出'lounge'的值

我的代码搜索它并找到“123456789”,但我似乎无法让它打印“lounge”!你知道吗

我相信这是一个简单的解决办法,但我似乎找不到答案!你知道吗

泰铢 马特。你知道吗

我也在这里放了一份副本;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]

Tags: the字符串代码inidmap字典location
2条回答

不要使用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))

相关问题 更多 >