无法将字符串附加到字典键

Sha*_*ram 1 python dictionary key append key-value

我已经编程了不到四个星期,遇到了一个我无法弄清楚的问题.我正在尝试将字符串值附加到现有字符串中,并在其中存储现有字符串,但如果键中已存在任何值,则"str object has no attribute'sadndnd".

我已经尝试将值转换为列表,但这也不起作用.我需要使用.append()属性,因为update只是替换clientKey中的值,而不是附加到已存储的任何值.在做了一些更多的研究之后,我现在明白我需要以某种方式拆分存储在clientKey中的值.

任何帮助将不胜感激.

data = {}

while True:

    clientKey = input().upper()
    refDate = strftime("%Y%m%d%H%M%S", gmtime())
    refDate = refDate[2 : ]
    ref = clientKey + refDate

    if clientKey not in data:
        data[clientKey] = ref

    elif ref in data[clientKey]:
        print("That invoice already exists")

    else:
        data[clientKey].append(ref)

        break
Run Code Online (Sandbox Code Playgroud)

kin*_*all 6

您不能.append()使用字符串,因为字符串不可变.如果希望字典值能够包含多个项目,则它应该是容器类型,例如列表.最简单的方法是首先将单个项目添加为列表.

if clientKey not in data:
    data[clientKey] = [ref]   # single-item list
Run Code Online (Sandbox Code Playgroud)

现在你可以data[clientkey].append()整天.

这个问题的一个更简单的方法是使用collections.defaultdict.当项目不存在时,它会自动创建项目,使您的代码更加简单.

from collections import defaultdict

data = defaultdict(list)

# ... same as before up to your if

if clientkey in data and ref in data[clientkey]:
    print("That invoice already exists")
else:
    data[clientKey].append(ref)
Run Code Online (Sandbox Code Playgroud)