A very simple 20-line country - a dictionary error in the search for the capital.

Asked 1 years ago, Updated 1 years ago, 94 views

// Enter code here
#A function that returns a city and country name when you type a city name
def city_country():
    city = input ("Please enter a city name :")
    city_country = {"Seoul" : "Korea", "Athens" : "Greece", "Paris" : "France", "Washington" : "United States", "London" : "United Kingdom", "Copenhagen" : "Denmark",
    "Berlin":"Germany,"Moscow":"Russia","Luxembourg":"Luxembourg,"Mexico City":"Mexico":"Monaco":"Daka":"Bangladesh","Hanoi":"Vietnam",
    "Brussels," "Brazilia," "Brazilia," "Brazil," "Riyad," "Saudi Arabia," "Mogadish," "Somalia," "Stockholom": "Sweden," "Switzerland," "Madrid," "Spain,"
    "Damascus":"Syria","Singapore":"Singapore","Dubai":"United Arab Emirates","Buenos Aires":"Argentina","Dublin":"Ireland","Kabul":"Afghanistan",
    "Algeria":"Algeria":"Canberra":"Australia":"Austria":"Amman":"Jordan":"Tashkent":"Uzbekistan":"Kiev":"Ukraine":"Baghdad":"Iraq",
    "Teheran":"Iran","Jerberm":"Israel":"Cairo":"Egypt":Roma":"Italy":"Mumbai":"India","Jakarta":"Indonesia","Tokyo":"Japan"

    if(city in city_country.keys()):
        print("\"+city+\"+" is the country of "+"\"+city_country[city]+\"+")
    elif(city in city_country.values()):
        print ("You entered the country, not the capital."")
        print("\"+city_country[city] +"\"+" capital is ""+"\"+city+"")
    else:
        print ("I'm sorry". The capital is not in our database.")

flag = 1
while(flag==1):
        city_country()

I know that there is an error when referring to the key value that is not in the dictionary, but why is there an error when this program is not even that? I even classified it as an if statement.

dictionary python

2022-09-22 18:38

1 Answers

I can see why you're confused by making a demo. It's correct that there is an error. Because If you ride elif here, the entered city is not a city, but a country name.So if you find city_country[city], you get an error that there is no such key.

After all, you have to find a key with a value in the list, and the shortest way to find it is by searching python get key by values for this old problem is :

# How do I get the "george" string with a value of 16 here?
mydict = {'george': 16, 'amber': 19}
# Finds in the list key array with the 'index' of 16 in the list value array.
print mydict.keys()[mydict.values().index(16)]


2022-09-22 18:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.