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

时间:2013-07-05 03:29:27

标签: python

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

例如

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

我的代码搜索并找到'123456789',但我似乎无法打印'休息室'!

我确信这是一个简单的解决方案,但我似乎无法找到答案!

THX 太

此处也有副本; 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]

2 个答案:

答案 0 :(得分:2)

不是使用any()来检查测试字符串是否在字典的键中,而是遍历dicitonary的键:

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

答案 1 :(得分: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))