You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python向字典追加值报错AttributeError: 'dict' object has no attribute 'append'

Hey there, let's break down that error and get your code working properly!

What's Causing the AttributeError?

Two key issues are triggering this error:

  • Dictionaries don't have an append() method
    The append() function is exclusive to Python lists. Your code is trying to call it on user['areas'], which is either a dictionary (hence the error) or you've mistakenly treated it like a list when it's not.
  • Syntax mistake in method call
    Even if user['areas'] were a list, append[temp] is wrong—method calls require parentheses (), not square brackets [] (brackets are used for accessing elements in lists/dictionaries).

On top of that, there's a redundant for item in user: loop in your code—you don't need to iterate over the user dictionary to add items to its areas key, which is just creating extra confusion.

Fixes to Get Your Logic Working

Let's walk through the fixes step by step:

  1. Ensure user['areas'] is initialized as a list
    First, make sure the areas key in your user dictionary points to an empty list (not a dict) from the start. If you haven't initialized user yet, do it like this:

    user = {'areas': []}
    

    If you were using the li variable earlier, you probably mixed up variable names—stick to one consistent name (either user or li) to avoid confusion.

  2. Fix the append syntax and remove the unnecessary loop
    Get rid of the for item in user: loop entirely, then correct the append call to use parentheses. Here's what that section of code should look like:

    while True:
        n = input('\nGive number: ')
        if n == "":
            break
        if n.isdigit():
            n = int(n)
            print('\n', main_feeds[n])
            temp = main_feeds[n]
            # Append directly to the areas list
            user['areas'].append(temp)
    
  3. Double-check variable consistency
    You initialized li = {} and passed it to print_user_areas(li), but then you're modifying user later. If li is supposed to be the same as user, rename one to match the other so your code doesn't have disconnected variables.

Quick Recap
  • Use append() only on lists, never dictionaries
  • Always use parentheses for method calls
  • Keep variable names consistent to avoid logic gaps

内容的提问来源于stack exchange,提问作者anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:10:36