0

尝试搜索我创建的名为 location_hw_map 的字典,我希望它能够在字符串“testString”中搜索其中一个单词,并在找到时返回该位置。

例如; 使用 testString 它应该打印出“休息室”的值

我的代码搜索它并找到“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]
4

2 回答 2

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
于 2013-07-05T03:31:03.413 回答
1
# 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))
于 2013-07-05T03:36:32.880 回答