Search code examples
pythondjangovariables

Python Return a Variable in the file


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
    ...

Solution

  • 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'),)
                  }