我正在创建一个循环,以便将来自用户输入的连续值附加到字典中,但出现以下错误:
AttributeError: 'dict' object has no attribute 'append'
到目前为止这是我的代码:
for index, elem in enumerate(main_feeds):
print(index,":",elem)
temp_list = index,":",elem
li = {}
print_user_areas(li)
while True:
n = (input('\nGive number: '))
if n == "":
break
else:
if n.isdigit():
n=int(n)
print('\n')
print (main_feeds[n])
temp = main_feeds[n]
for item in user:
user['areas'].append[temp]
有什么想法吗?
或者 如果尚未将密钥添加到字典中,请使用dict.setdefault():
或者,如果您已经设置了密钥,请使用:
来源:stackoverflow answers
与错误消息所暗示的一样,Python中的字典不提供append操作。
相反,您可以在字典中为它们各自的键指定新值。
如果希望在输入值时追加值,则可以使用列表。
您的行
user['areas'].append[temp]
看起来正试图访问键'areas'
值的字典,如果您改为使用列表,则应该能够执行追加操作。改为使用列表:
在这一点上,您可能想检查一下使用
defaultdict(list)
解决问题的可能性。See here相关问题 更多 >
编程相关推荐