今天要跟大家介紹Python dict物件的一個方法dict.copy()
以下是官方文件的介紹
Return a shallow copy of the dictionary.
描述
Python 字典(Dictionary) copy() 函数回傳一個字典的複製。
語法
dict.copy()
參數
- NA
回傳值
回傳一個字典的複製。
實例
dict1 = {'name': 'Jack', 'height': 175, 'weight': 75}
dict2 = dict1.copy()
#{'name': 'Jack', 'height': 175, 'weight': 75} {'name': 'Jack', 'height': 175, 'weight': 75}
print(dict1, dict2)
#139793342545504 139793275841024(二字典記憶體位置不相同)
print(id(dict1), id(dict2))
dict2['sex']='male'
#{'name': 'Jack', 'height': 175, 'weight': 75, 'sex': 'male'}
print(dict2)
#139793342545504 139793275841024(二字典記憶體位置不相同,互相不受影響)
print(id(dict1), id(dict2))