如何为字典重复键添加值并实现键存储多值列表
问题解决:字典键存在时将值转为列表存储
错误原因
你代码里的allpasswords["bob"]初始值是字符串类型,而append()是列表专属方法,字符串调用该方法必然触发AttributeError: 'str' object has no attribute 'append'。
解决方案
方案1:初始化字典时统一用列表存储值
这种方法从根源上统一值的类型,避免后续类型判断:
def storingPassword(): username = "bob" password = "PASSWORD1" allpasswords = { "jeff": ["jeff 123 "], "bob": ["bob 123"] } if username not in allpasswords: allpasswords[username] = [password] else: allpasswords[username].append(password) return allpasswords
方案2:动态转换现有值的类型
如果需要保留原字典的字符串初始值,可以在添加新值前判断并转换类型:
def storingPassword(): username = "bob" password = "PASSWORD1" allpasswords = { "jeff": "jeff 123 ", "bob": "bob 123" } if username not in allpasswords: allpasswords[username] = password else: # 若当前值不是列表,先转为列表 if not isinstance(allpasswords[username], list): allpasswords[username] = [allpasswords[username]] allpasswords[username].append(password) return allpasswords
运行结果
执行上述任意一种方案后,函数返回结果符合预期:
{ "jeff": "jeff 123 ", "bob": ["bob 123", "PASSWORD1"] }
内容的提问来源于stack exchange,提问作者Zak345
相关产品推荐
相关产品推荐

