【问题标题】:Python AttributeError: 'dict' object has no attribute 'append'Python AttributeError:“dict”对象没有属性“append”
【发布时间】:2018-06-22 09:37:00
【问题描述】:

我正在创建一个循环,以便将用户输入中的值连续附加到字典,但我收到此错误:

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 没有 append 方法。即使是这样,你也不能用方括号来调用它。
  • 使用 defaultdict 代替(其中包含列表)
  • 您使用字典的键为字典赋值:user['areas'] = temp。只有当 user[areas] 已经是一个列表时,您的代码才能工作。如果您需要它是一个列表,请先构建列表,然后将该列表分配给键。

标签: python dictionary for-loop tuples


【解决方案1】:

如错误消息所示,Python 中的字典不提供追加操作。

您可以改为将新值分配给字典中它们各自的键。

mydict = {}
mydict['item'] = input_value

如果您想在输入值时附加值,您可以改用列表。

mylist = []
mylist.append(input_value)

您的user['areas'].append[temp] 行似乎正在尝试访问键值为'areas' 的字典,如果您改为使用列表,您应该能够执行追加操作。

使用列表代替:

user['areas'] = []

在此说明中,您可能想检查一下使用defaultdict(list) 解决您的问题的可能性。 See here

【讨论】:

  • Python 中的字典 do 提供了一个 update 方法。所以,如果你想添加更多的键值对:dict.update({'another_key': 'another_value'})。也许在这里有价值。 update 将覆盖现有的同名键,所以caveat emptor
  • 非常真实的马特!不过,看起来他们只是想在此处附加值。
【解决方案2】:

正如错误提示的那样,append 不是方法或属性,这意味着您不能在字典 user 中调用 append。 而不是

user['areas'].append[temp]

使用

user['areas'].update[temp]

【讨论】:

    【解决方案3】:

    要么 如果键尚未添加到字典中,请使用 dict.setdefault() :

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

    或使用,如果您已经设置了密钥:

    dict[key].append(value)
    

    来源:stackoverflow 答案

    【讨论】:

    • 您至少应该添加一个链接,指向您所指的 stackoverflow 的答案
    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 2020-11-07
    • 2020-09-11
    • 2015-08-16
    • 2017-08-14
    • 2015-03-08
    • 2019-03-11
    • 2018-10-13
    相关资源
    最近更新 更多