Python:値をデープコピーしたい

copy.deepcopy を使えば良い。

import copy
import json

value = {
  "name": "Yamada",
  "gender": "male",
  "address": {
    "country": "Japan",
    "Prefecture": "Saitama",
  }
}

dup1 = copy.deepcopy(value)
dup1["name"] = "Suzuki"
dup1["address"]["Prefecture"] = "Tokyo"
print(json.dumps(dup1, indent=2))
print(json.dumps(value, indent=2))
{
  "name": "Suzuki",
  "gender": "male",
  "address": {
    "country": "Japan",
    "Prefecture": "Tokyo"
  }
}
{
  "name": "Yamada",
  "gender": "male",
  "address": {
    "country": "Japan",
    "Prefecture": "Saitama"
  }
}
Docker Desktop for Windows/Macでつくるクリーンな開発環境構築入門(Python版) (Amazon)

コメント