在前一篇文章 python ChainMap 中我們介紹了關於python內置函數 ChainMap的使用,ChainMap函數和update函數類似,都是對字典操作,也是將多個字典合並,那么問題來了?ChainMap和update兩者區別在哪呢?
一.update簡介
python 字典(Dictionary) update() 函數把字典dict的鍵/值對更新到另外一個dict里。
dict1= {"a":"zhangsan","b":"lisi"} dict2= {"c":"wangwu"} # 合並字典 dict2.update(dict1) print(dict2)
輸出結果:
{'c': 'wangwu', 'a': 'zhangsan', 'b': 'lisi'}
二.update和ChainMap區別
1.內置函數ChainMap函數對多個字典合並時,合並的結果內存地址並沒有發生改變,當我們修改ChainMap函數返回的結果時,會發現原始字典的數據也會發生相同的變化;當我修改原始字典時,ChainMap函數返回的結果也會跟隨一起變化,這也意味着:ChainMap函數返回的結果和原始字典共用一塊內存地址。
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:何以解憂 @Blog(個人博客地址): shuopython.com @WeChat Official Account(微信公眾號):猿說python @Github:www.github.com @File:python_chainmap.py @Time:2019/11/22 21:25 @Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累! """ from collections import ChainMap dict1= {"a":"zhangsan","b":"lisi"} dict2= {"c":"wangwu"} # 合並字典 new_dict = ChainMap(dict1,dict2) print(new_dict) print("***"*20) # 修改數據 new_dict.maps[0]["a"] = "123" print(new_dict) print(dict1)
輸出結果:
ChainMap({'a': 'zhangsan', 'b': 'lisi'}, {'c': 'wangwu'}) ************************************************************ ChainMap({'a': '123', 'b': 'lisi'}, {'c': 'wangwu'}) {'a': '123', 'b': 'lisi'}
2.update函數將原始字典dict的鍵/值對更新到另外一個目標dict里,合並之后原始字典dict和目標字典都是獨立的內存塊,兩者互不影響!
3.ChainMap函數可以同時合並多個字典,update函數每次只能合並一個字典!
猜你喜歡:
轉載請注明:猿說Python » python update
技術交流、商務合作請直接聯系博主
掃碼或搜索:猿說python

猿說python
微信公眾號 掃一掃關注