Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a dictionary to a list through a function

So I have been practicing some coding in Python. I came to a task where I was supposed to add a dictionary to an existing list (which had dictionaries).

The given function (at the end) works, but when I tried to write the following (in the function)

    travel_log.append(add_new_country)

instead of

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    travel_log.append(country)
    travel_log.append(visits)
    travel_log.append(cities)

and then try to print out travel_log, I would get the following (look at the last dictionary in the list):

[{'country': 'France', 'visits': 12, 'cities': ['Paris', 'Lille', 'Dijon']}, {'country': 'Germany', 'visits': 5, 'cities': ['Berlin', 'Hamburg', 'Stuttgart']},<function add_new_country at 0x7fefd60e8310>]

Can somebody explain why does that happen?

Full code:

    travel_log = [
    {
    "country": "France",
    "visits": 12,
    "cities": ["Paris", "Lille", "Dijon"]
    },
    {
    "country": "Germany",
    "visits": 5,
    "cities": ["Berlin", "Hamburg", "Stuttgart"]
    },
    ]


    def add_new_country(country,visits,cities):
    travel_log.append(country)
    travel_log.append(visits)
    travel_log.append(cities)

    add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
    print(travel_log)

>Solution :

You need to create a dictionary and add it to travel_log (list),

def add_new_country(country,visits,cities):
    d = {'country': country, 'visits': visits, 'cities': cities}
    travel_log.append(d)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading