Python向字典追加值报错AttributeError: 'dict' object has no attribute 'append'
Hey there, let's break down that error and get your code working properly!
AttributeError? Two key issues are triggering this error:
- Dictionaries don't have an
append()method
Theappend()function is exclusive to Python lists. Your code is trying to call it onuser['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 ifuser['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.
Let's walk through the fixes step by step:
Ensure
user['areas']is initialized as a list
First, make sure theareaskey in youruserdictionary points to an empty list (not a dict) from the start. If you haven't initializeduseryet, do it like this:user = {'areas': []}If you were using the
livariable earlier, you probably mixed up variable names—stick to one consistent name (eitheruserorli) to avoid confusion.Fix the
appendsyntax and remove the unnecessary loop
Get rid of thefor 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)Double-check variable consistency
You initializedli = {}and passed it toprint_user_areas(li), but then you're modifyinguserlater. Ifliis supposed to be the same asuser, rename one to match the other so your code doesn't have disconnected variables.
- Use
append()only on lists, never dictionaries - Always use parentheses for method calls
- Keep variable names consistent to avoid logic gaps
内容的提问来源于stack exchange,提问作者anonymous

