将dictionarys项设置为变量

时间:2014-09-28 15:13:42

标签: python dictionary

我想知道这是否可行,将字典项保存到变量中。所以这就是我正在做的事情。我将此项目保存到字典中:

accounts{}

def accountcreator():
  newusername = raw_input()
  newpassword = raw_input()
  UUID = 0
  UUID += 1
  accounts[newusername] = {newpassword:UUID}

现在基本上我将在一个单独的函数中循环遍历新用户名:

def accounts():
  username = raw_input()
  for usernames in accounts:
    if usernames == username:
      #Not sure what to do from here on out
    else:
      accounts()

这是我感到困惑的地方。因此,如果用户名输入等于帐户字典中的新用户名,则它将继续。我希望它将新用户名密码和UUID({newpassword:UUID}部分)保存到变量中。所以基本上如果newusername等于用户名输入,它会将其余的信息({newpassword:UUID})保存到变量中。所以最后变量让我们说 accountinfo = {newpassword:UUID} 。谢谢,我希望这是有道理的。

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些错误。首先,可能是一个错字:

accounts = {}

接下来,当您创建代码时,总是UUID重置为0,使增量略显无效。在函数外部初始化UUID,就像使用accounts

一样
UUID = 0
def accountcreator():
    newusername = raw_input()
    newpassword = raw_input()
    UUID += 1
    accounts[newusername] = {newpassword:UUID}

第三,我不确定为什么要将密码映射到UUID。可能,您希望用户词典中的两个单独字段存储两者:

    accounts[newusername] = { 'password': newpassword, 'UUID': UUID }

最后,使用字典将用户名映射到信息的全部意义在于,您不需要遍历整个字典;您只需使用用户名索引字典。但是,您必须注意不要尝试访问不存在的密钥。

# Use a different name; accounts is already a dictionary
def get_account():
    username = raw_input()
    if username in accounts:
        return accounts[username]
    else:
        print("No account for {0}".format(username))