【问题标题】:Nonetype is not iterable when updating dictionary?更新字典时Nonetype不可迭代?
【发布时间】:2019-03-09 06:32:19
【问题描述】:

我对 python 很陌生,作为一个推动自己的项目,我决定创建一个带有可更新用户:密码字典的简单框架。 这项工作仍在进行中! 创建新用户 ID 然后尝试访问该用户 ID 时存在问题。我正在使用python 3.7。

这是错误: 回溯(最近一次通话最后): 第 37 行,在 如果帐户中的帐户: TypeError:“NoneType”类型的参数不可迭代

import sys
accounts = {'Trace': 'Jollyrancher5', 'Brian': 'Kitties82', 'Taylor': 'Flower15'}

while True:
    print('Please select an option.\n1. Create new account.\n2. Enter existing account.')
    choice = input()
    if choice == '1':
        print('Please enter an account name')
        new_account = input()
        if new_account not in accounts.keys():
            print('Please enter a password.')
            new_pass = input()
            accounts = accounts.update({new_account: new_pass})
            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.')
        else:
            print('Account name taken. Please enter a different account name.')
    elif choice == '2':
        break
    else:
        print('Not a valid entry.')

account = ''
password = ''
denial = 0
while True:
    print('Please enter User ID.')
    account = input()
    if account in accounts:
        break
    else:
        print('User ID not recognized.')

while True:
    print('Please enter password.')
    password = input()
    if password == accounts[account]:
        break
    else:
        password != accounts[account]
        denial += 1
        if denial == 3:
            print('Account locked.')
            input()
            sys.exit()
print('Access Granted.\nYour account balance is $1,000,000.00.')
input()

【问题讨论】:

  • 第 13 行返回 None 只使用 accounts.update(...) 而不是 accounts = accounts.update(...)
  • accounts = accounts.update({...}) -> accounts.update({...}).

标签: python python-3.x


【解决方案1】:

问题在第 13 行:

accounts = accounts.update({new_account: new_pass})

这会在更新完成后返回None。 [see docs] 改为使用:

accounts.update({new_account: new_pass})

它将执行更新,无需重新分配值。

【讨论】:

  • 啊,这么简单,我怎么没有意识到。非常感谢!
  • @Jab 我终于得到了我的 python gold-tag-badge :-) 和 16k 终于 :-)
【解决方案2】:

删除这一行:-

`accounts = accounts.update({new_account: new_pass})`

添加这一行:-

`while True:
      print('Please enter User ID.')
      account = input()
      accounts.update({new_account:new_pass})
      if account in accounts:`

这个错误是因为你的字典没有得到更新,这就是为什么它收到的第一个值是 None 因此生成了 NoneType 错误。

如果你理解我的回答,请点赞。

【讨论】:

    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 2019-10-23
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多