往dictionary加新的key,为什么要在前面加def

问题是,已经有了一个字典叫travel_log,然后我想加新的key进去,但是为什么要在空字典new_country前面加一个def呢,为什么不直接写一个空的字典然后直接赋值,我知道我的不对,但是我不明白为什么要加def

我的


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

#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇

  new_country = {}
  new_country["country"] = Russia
  new_country["visits"] = 12
  new_country["cities"] = Moscow, Saint Petersburg
  travel_log.append(new_country)

print(travel_log)

正确的


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

#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇

def add_new_country(country_visits, times, cities_visits):
  new_country = {}
  new_country["country"] = country_visits
  new_country["visits"] = times
  new_country["cities"] = cities_visits
  travel_log.append(new_country)

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

这其实并不是def的问题,而是python基础语法 缩进的问题

def foo():
····pass

这四个点就代表四个空格,你可以把 所有缩进去掉 同时去掉def 其他语言中语法块用{ } 这种 python中用四个空格,四个空格代表 一个作用域,下面这样去掉def的作用域也是可以的

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


# TODO: Write the function that will allow new countries
# to be added to the travel_log. 👇


new_country = {}
new_country["country"] = "Russia"
new_country["visits"] = 2
new_country["cities"] = ["Moscow", "Saint Petersburg"]
travel_log.append(new_country)

print(travel_log)

你的答案没错。只不过如果需要输入多条记录的话,需要重复书写很多遍。
而题目考的是函数的封装,是希望你把同样的命令放在一个自定义函数里,这样下次输入记录的时候,只要调用这个函数传参就可以了。
另外如果你刷力扣或其他题库的话,都是要求你把语句封装成函数或者类。
这只是题目的要求,并不代表你的语法错了。

补充一下:你的答案里,字典的值,应该是字符串,需要加双引号,列表的话还需要加中括号。不过我相信是笔误。