當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。