【发布时间】:2014-07-05 03:38:31
【问题描述】:
我编程不到四个星期,遇到了一个我无法弄清楚的问题。我正在尝试将一个字符串值附加到一个现有的键中,其中存储了一个现有的字符串,但是如果键中已经存在任何值,我会得到“str object has no attribute 'append'。
我尝试将值转换为列表,但这也不起作用。我需要使用 .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
【问题讨论】:
-
非常感谢大家的帮助。它正在按应有的方式运行。我也很欣赏关于 defaultdict 的建议。这听起来像是一种简化和压缩代码的明智方法。
标签: python dictionary key append key-value