日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python字典副本_如何复制字典并仅在Python中编辑副本?

發(fā)布時間:2025/3/11 python 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python字典副本_如何复制字典并仅在Python中编辑副本? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

python字典副本

Python never implicitly copies the dictionary or any objects. So, while we set dict2 = dict1, we're making them refer to the same dictionary object. Hence, even when we mutate the dictionary, all the references made to it, keep referring to the object in its current state.

Python絕不會隱式復制字典或任何對象。 因此,當我們設置dict2 = dict1時 ,我們使它們引用相同的字典對象。 因此,即使我們對字典進行了變異,對其的所有引用也會繼續(xù)引用該對象的當前狀態(tài)。

dict1 = {"key1": "abc", "key2": "efg"}dict2 = dict1print(dict1) print(dict2)dict2['key2'] = 'pqr'print(dict1) print(dict2)

Output

輸出量

{'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'pqr'} {'key1': 'abc', 'key2': 'pqr'}

To copy a dictionary, either uses a shallow copy or deep copy approach, as explained in the below example.

要復制字典 ,請使用淺層復制或深層復制方法 ,如以下示例中所述。

使用淺拷貝 (Using shallow copy)

dict1 = {"key1": "abc", "key2": "efg"}print(dict1)dict3 = dict1.copy() print(dict3)dict3['key2'] = 'xyz'print(dict1) print(dict3)

Output

輸出量

{'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'xyz'}

使用深度復制 (Using deep copy)

import copydict1 = {"key1": "abc", "key2": "efg"}print(dict1)dict4 = copy.deepcopy(dict1) print(dict4)dict4['key2'] = 'test1'print(dict4) print(dict1)

Output

輸出量

{'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'efg'} {'key1': 'abc', 'key2': 'test1'} {'key1': 'abc', 'key2': 'efg'}

翻譯自: https://www.includehelp.com/python/how-to-copy-a-dictionary-and-only-edit-the-copy.aspx

python字典副本

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結

以上是生活随笔為你收集整理的python字典副本_如何复制字典并仅在Python中编辑副本?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。