Skip to main content
 首页 » 编程设计

python之无法将字符串 append 到字典键

2025年05月04日29lyj

我编程不到四个星期就遇到了一个我无法解决的问题。我正在尝试将一个字符串值 append 到一个现有的键,其中存储了一个现有的字符串,但是如果键中已经存在任何值,我会得到“str object has no attribute 'append'。

我试过将值转换为列表,但这也不起作用。我需要使用 .append() 属性,因为更新只是替换 clientKey 中的值,而不是 append 到已存储的任何值。在做了更多研究之后,我现在明白我需要以某种方式拆分存储在 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 

请您参考如下方法:

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

if clientKey not in data: 
    data[clientKey] = [ref]   # single-item list 

现在您可以整天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)