【问题标题】:Why is there an Attribute Error: 'str' object has no attribute 'copy' for this code?为什么会出现属性错误:“str”对象没有此代码的属性“copy”?
【发布时间】:2022-01-04 13:20:18
【问题描述】:

尝试在不使用复制模块的情况下创建字典的深层副本。

def deepcopy(data: dict):
    copy_dict = {}

    for keys, values in data.items():
        new_value = values.copy()
        copy_dict[keys] = new_value

    return copy_dict


old = {"Lion": "brave", "Tiger": "striped"}
copied_dict = deepcopy(old)
print(copied_dict)

这是我得到的错误:

line 11, in deepcopy
    new_value = values.copy()
AttributeError: 'str' object has no attribute 'copy'

我应该能够创建“值”的副本,但我收到此错误消息。

【问题讨论】:

  • 你的价值观是“勇敢”和“条纹”,这两者都不是列表
  • 您好像忘记发布函数标题了。

标签: python string list dictionary deep-copy


【解决方案1】:

不,keysvalues 都将是字符串。循环体对每个键/值对执行一次,变量设置为它所在的任何一对,而不是一次全部执行。

【讨论】: