Home > Mobile >  How do I solve this exercise without creating redundant elements in my dictionary with Python?
How do I solve this exercise without creating redundant elements in my dictionary with Python?

Time:01-06

I am preparing for an exam of basic python programming, and this is one of the exercises in preparation for it:

Countries and cities are listed in file "countries.txt". On each line, there is the name of a country and some cities of the country. For example,

USA Boston Pittsburgh Washington Seattle
UK London Edinburgh Cardiff Belfast

Write a program that repeatedly prompts the user for the name of a city and outputs the country in which the city is located. If the user enters a city that is not mentioned in the file, then the program outputs "No information about the city ...". The program continues asking the user for a city until the user enters “done”.

An example of the program output (using the above-mentioned file):

 Please enter the name of a city: Cardiff
 Cardiff is in UK
 Please enter the name of a city: Seattle
 Seattle is USA
 Please enter the name of a city: Moscow
 No information about Moscow
 Please enter the name of a city: London
 London is in UK
 Please enter the name of city: done

This is how I solved it

handle = open('countries.txt')

pair = dict()
for line in handle:
    line = line.split()
    for word in line:
        pair[word] = line[0]
        
    
while True:
    city = input('Enter city: ')
    if city in pair:
        print(pair[city])
    elif city == 'done':
        break
    elif city not in pair:
        print('No info')

handle.close()

But this way, if I print the dictionary I created, there are also some key/value pairs that are both the name of the country, like 'USA':'USA', as you can see:

pair = {'USA': 'USA', 'Boston': 'USA', 'Pittsburgh': 'USA', 'Washington': 'USA', 'Seattle': 'USA', 'UK': 'UK', 'London': 'UK', 'Edinburgh': 'UK', 'Cardiff': 'UK', 'Belfast': 'UK'}

This doesn't seem a very elegant solution, as some pairs are created and not going to be used, or if the user enters a country instead of a city, the program is going to give back the same country.

Maybe dictionaries are not the best way to solve this?

Thank you for your help!

CodePudding user response:

Use a slice to skip over the country name:

    for word in line[1:]:

Or you can use spread assignment:

country, *cities = line.split():
for city in cities:
    pair[country] = city

CodePudding user response:

What you need is called list licing.

Change your

for word in line:
    pair[word] = line[0]

into

for word in line[1:]:
    pair[word] = line[0]

and you'll get the same dictionary you're getting without the country appearing as a city because you're iterating over the sublist of line obtained by excluding its first element.

  • Related