Python AttributeError: 'dict' object has no attribute 'append'

狂风中的少年 提交于 2020-04-29 08:48:26

问题


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?


回答1:


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)

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.

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




回答2:


Either use dict.setdefault() if the key is not added yet to dictionary :

dict.setdefault(key,[]).append(value)

or use, if you already have the keys set up:

dict[key].append(value)

source: stackoverflow answers



来源:https://stackoverflow.com/questions/48234473/python-attributeerror-dict-object-has-no-attribute-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!