2

I have tuple variables which are France, Germany. I'm trying to give a value to my bring_cities function and if it's France or Germany, I like to see the France and Germany tuple objects. Is there any shortcut to not use if loops like I did in the below ?

France = (
    ('Paris', 'Paris'),
    ('Lyon', 'Lyon'),
)
Germany = (
    ('Frankfurt', 'Frankfurt'),
    ('Berlin', 'Berlin'),
)

cities = (('', ''),) + France + Germany

def bring_cities(country): 
    if country == 'France':
        return France
    if country == 'Germany':
        return Germany
    ...
1
  • 2
    You could store the tuples in a dict and access them by key (country). Commented Feb 22, 2022 at 11:53

2 Answers 2

4

You can create a dictionary so you don't have to write an if statement for each country. You can use the following code for that.

France = (
    ('Paris', 'Paris'),
    ('Lyon', 'Lyon'),
)
Germany = (
    ('Frankfurt', 'Frankfurt'),
    ('Berlin', 'Berlin'),
)

dictionary = {"France": France, "Germany": Germany}


def bring_cities(country):
    return dictionary[country]

to make it even shorter you can define your Countries inside the dictionary.

dictionary = {
              "France": (('Paris', 'Paris'), ('Lyon', 'Lyon')),
              "Germany": (('Frankfurt', 'Frankfurt'), ('Berlin', 'Berlin'),)
              }
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your help gerda. there will be all countries and cities in my code. so is it possible to make it a bit shorter ?
0

Resuming gerda's answer

France = (
    ('Paris', 'Paris'),
    ('Lyon', 'Lyon'),
)
Germany = (
    ('Frankfurt', 'Frankfurt'),
    ('Berlin', 'Berlin'),
)

dictionary = {"France": France, "Germany": Germany}


def bring_cities(country):
    print(dictionary[country])
    
user_choice = input("Enter a Country (France/Germany) and we will give you Cities in it: ")
bring_cities(user_choice)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.