当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python Dictionary update()用法及代码示例

字典 update() 方法

update() 方法用于通过向字典中插入新项目来更新字典。

用法:

    dictionary_name.setdefault(iterable)

参数:

  • iterable– 它代表一个迭代对象或一个要插入到字典中的字典。

返回值:

它什么都不返回。

例:

# Python Dictionary update() Method with Example

# dictionary declaration
student = {
  "roll_no":101,
  "name":"Shivang",
  "course":"B.Tech",
  "perc":98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# inserting an item
student.update({'city':'Indore'})

# printing dictionary after update()
print("data of student dictionary after update()...")
print(student)

# inserting multiple items
student.update({'city':'Indore', 'address':'Tech park'})

# printing dictionary after update()
print("data of student dictionary after update()...")
print(student)

输出

data of student dictionary...
{'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5}
data of student dictionary after update()...
{'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5, 'city':'Indore'}
data of student dictionary after update()...
{'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5, 'city':'Indore', 'address':'Tech park'}


相关用法


注:本文由纯净天空筛选整理自 Python Dictionary update() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。