Search code examples
pythondictionarytypeerror

typeError while adding items to list through a function


so currently im working on a function where you add countries you visit, times visited and cities visited to a list however whenever i add the arguments to the list through the function i get a type error

here is my code ps: im still learning and the requirements are that i have to add the items through a function

code

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#🚨 Do NOT change the code above
def add_new_country(country, times_visited, cities_visited):
    travel_log["country"] = country
    travel_log["times_visited"] = times_visited
    travel_log["Cities_visited"] = cities_visited
    

#🚨 Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

Error

Traceback (most recent call last):
  File "C:\Users\(my name is here)\2.py", line 21, in <module>
    add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
  File "C:\Users\(also my name)\2.py", line 15, in add_new_country
    travel_log["country"] = country
TypeError: list indices must be integers or slices, not str

Solution

  • You can append a dict to list:

    def add_new_country(country, times_visited, cities_visited):
         travel_log.append({'country': country, 'visits': times_visited, 'cities': cities_visited})