m0_61637220 2022-05-04 13:05 采纳率: 66.7%
浏览 20
已结题

往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)
  • 写回答

2条回答 默认 最新

  • 我不喜欢这个世界 2022-05-04 13:19
    关注

    这其实并不是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)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月12日
  • 已采纳回答 5月4日
  • 创建了问题 5月4日

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line