首页 > 编程语言 >python中如何更新字典的元素

python中如何更新字典的元素

时间:2022-08-15 14:24:18浏览次数:52  
标签:test1 python 元素 300 400 100 ## 字典

 

001、 直接利用索引实现

>>> test1 = {"a":100, "b":200, "c":300, "d":400}                   ## 测试字典
>>> test1
{'a': 100, 'b': 200, 'c': 300, 'd': 400}
>>> test1["b"] = 8888                                              ## 更新字典中b的值
>>> test1
{'a': 100, 'b': 8888, 'c': 300, 'd': 400}
>>> test1["e"] = 9999                                              ## 当字典中不存在相应键时, 则直接向字典中添加元素
>>> test1
{'a': 100, 'b': 8888, 'c': 300, 'd': 400, 'e': 9999}

 

002、利用字典内置函数update()实现

>>> test1 = {"a":100, "b":200, "c":300, "d":400}                   ## 测试字典
>>> test1
{'a': 100, 'b': 200, 'c': 300, 'd': 400}
>>> test1.update(b = 777777)                                       ## 更新字典中b的值
>>> test1
{'a': 100, 'b': 777777, 'c': 300, 'd': 400}
>>> test1.update(e = 9999)                                         ## 当字典中不存在相应键时,则直接向字典中添加元素
>>> test1
{'a': 100, 'b': 777777, 'c': 300, 'd': 400, 'e': 9999}

 

标签:test1,python,元素,300,400,100,##,字典
From: https://www.cnblogs.com/liujiaxin2018/p/16588140.html

相关文章