Python AttributeError:"dict"对象没有属性"append" [英] Python AttributeError: 'dict' object has no attribute 'append'
问题描述
我正在创建一个循环,以便将来自用户输入的值连续追加到字典中,但出现此错误:
I am creating a loop in order to append continuously values from user input to a dictionary but i am getting this error:
AttributeError: 'dict' object has no attribute 'append'
到目前为止,这是我的代码:
This is my code so far:
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]
有什么想法吗?
推荐答案
就像错误消息所暗示的那样,Python中的字典不提供附加操作.
Like the error message suggests, dictionaries in Python do not provide an append operation.
您可以只为字典中的相应键分配新值.
You can instead just assign new values to their respective keys in a dictionary.
mydict = {}
mydict['item'] = input_value
如果您希望在输入值时附加值,则可以使用列表.
If you're wanting to append values as they're entered you could instead use a list.
mylist = []
mylist.append(input_value)
您的行user['areas'].append[temp]
似乎正在尝试使用键'areas'
的值访问字典,如果您改为使用列表,则应该能够执行追加操作.
Your line user['areas'].append[temp]
looks like it is attempting to access a dictionary at the value of key 'areas'
, if you instead use a list you should be able to perform an append operation.
改为使用列表:
user['areas'] = []
关于该注释,您可能希望检查使用defaultdict(list)
解决问题的可能性. 在此处查看
On that note, you might want to check out the possibility of using a defaultdict(list)
for your problem. See here
这篇关于Python AttributeError:"dict"对象没有属性"append"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!