Python AttributeError:'dict'对象没有属性'append'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48234473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python AttributeError: 'dict' object has no attribute 'append'
提问by anonymous
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]
Any ideas?
有任何想法吗?
回答by Shane Williamson
Like the error message suggests, dictionaries in Python do not provide an append operation.
就像错误消息所暗示的那样,Python 中的字典不提供追加操作。
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)
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'].append[temp]
看起来像是试图以 key 的值访问字典'areas'
,如果您改为使用列表,则应该能够执行追加操作。
Using a list instead:
改用列表:
user['areas'] = []
On that note, you might want to check out the possibility of using a defaultdict(list)
for your problem. See here
在这一点上,您可能想要检查使用 adefaultdict(list)
解决您的问题的可能性。看这里
回答by sivi
Either use dict.setdefault() if the key is not added yet to dictionary :
如果键尚未添加到字典中,请使用 dict.setdefault() :
dict.setdefault(key,[]).append(value)
or use, if you already have the keys set up:
或使用,如果您已经设置了密钥:
dict[key].append(value)
source: stackoverflow answers
来源:stackoverflow 答案