Python更新字典时触发‘NoneType不可迭代’错误求助
Hey there! Let's break down what's causing that error and how to fix it quickly.
The root of your problem is this line in the "Create new account" section:
accounts = accounts.update({new_account: new_pass})
Here's why it's breaking things: Python's dict.update() method modifies the dictionary in-place (it changes the original accounts dictionary directly) and returns None. When you assign the result back to accounts, you're replacing your valid dictionary with None. Later, when you try to check if account in accounts, you're trying to iterate over None, which throws that TypeError.
The Fix
Just remove the assignment. Change that line to:
accounts.update({new_account: new_pass})
This way, you modify the original accounts dictionary without overwriting it with None. Your code will keep the updated dictionary, and the check if account in accounts will work as expected after creating a new user.
Let's Verify the Corrected Code Snippet
Here's the fixed part of your code for creating accounts:
if new_account not in accounts.keys(): print('Please enter a password.') new_pass = input() accounts.update({new_account: new_pass}) # No assignment here! print('Your new User ID is: ' + new_account + '.') print('Your new password is: ' + new_pass + '.') print('Please store this information for safe keeping.') print('Type OK to continue.') while True: next = input() if next == 'OK' or next == 'ok': break else: print('Invalid entry. Please type OK.')
After making this change, when you create a new account, accounts will still be a valid dictionary, and you'll be able to access the new user ID without hitting that error.
内容的提问来源于stack exchange,提问作者Trace R.

