0

私が作成した location_hw_map という名前の辞書を検索しようとすると、文字列 'testString' で単語の 1 つを検索できるようになり、見つかったときに場所が返されます。

例えば; 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]
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 に答える