0

だから私はこれらの値を持つ辞書を持っています:

{'AFG': (13, 0, 0, 2), 'ALG': (15, 5, 2, 8), 'ARG': (40, 18, 24, 28)}

そして、ユーザーが 3 文字の用語のタプルを知りたいとします。ええと、彼または彼女は「AFG」とパンチインすると、出力されます。[AFG, (13,0,0,2)]

ただし、一致が見つからないコードが表示されます。

何が起こっている?辞書にあるとおりに名前を打ち込んでいますが、探しているスペースやその他の空白文字はありません。

私のコード:

def findMedals(countryDict, medalDict):
    answer = [['Code','country','Gold','Silver','Bronze']]

    search_str = input('What is the country you want information on? ')

    #this block of code gets the country's name and three letter code onto the list
    for code, country in countryDict.items():
        if code == search_str:
            #This block should be getting executed if I type in, say, AFG
            answer = [['country','code'], [country,code]]
            print (answer)
        else:   
            #but this is being ran instead
            answer = [['country','code'], ['INVALID CODE', 'n/a']]
            #return answer


    print (medalDict) #debug code
    #this block goes and appends the medal count to the list
    for code, medalCount in medalDict.items():
        if search_str in code:
         #this block should be getting executed

            answer.append([medalCount])
        else:
            #it will still put in the AFG's medal count, but with no match founds.
            answer.append(['No Match Found'])
    print (answer) #debug code

forループのelse文と関係があるのではないかと思いますが、ループの外に出しても効果がないようです。

4

1 に答える 1

0

辞書内のすべてのキーと値をループしています。これは、一致しないelseループ内のすべてのキーに対してブロックが呼び出されることを意味します。

for code, country in countryDict.items():
    if code == search_str:
        #This block should be getting executed if I type in, say, AFG
        answer = [['country','code'], [country,code]]
        print (answer)
    else:   
        #but this is being ran instead
        answer = [['country','code'], ['INVALID CODE', 'n/a']]
        #return answer

ループオーバーされた最初のキーと値のペアが一致しない場合、elseブロックが実行され、戻ってきたように見えます。

ディクショナリで一致するキーを探すには、それをテストするかin、メソッドを使用し.get()て値またはデフォルトを取得します。

if search_key in countryDict:
    answer = [['country','code'], [search_key, countryDict[search_key]]
else:
    answer = [['country','code'], ['INVALID CODE', 'n/a']]

または使用:

country = countryDict.get(search_key)
if country:
    answer = [['country','code'], [country, search_key]]
else:
    answer = [['country','code'], ['INVALID CODE', 'n/a']]
于 2013-07-19T13:20:58.440 に答える