在函数中循环使用值

时间:2014-09-28 01:31:17

标签: python dictionary

所以我需要在字典中循环浏览字典词典。基本上我将这样的信息保存到字典中:

accounts = {}

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

然后在另一个函数中我想循环遍历所有这些值,所以例如这是我到目前为止所拥有的。这正确地循环遍历所有新用户名。

def accounts():
  for usernames in accounts:
    #I do not know what to do from here on out
    #I want it to loop through all of the newpasswords and UUID
    #And the UUIDs would be saved to a new variable

请帮助我,我只想简单回答一下如何遍历所有值。 谢谢!

修改 所以基本上这是一个例子:

def accountcreator():
  newusername = raw_input() #For raw input I put in cool-account-name
  newpassword = raw_input() #For raw input I put in this-is-a-password
  UUID = 0
  UUID += 1
  accounts[newusername] = {newpassword:UUID} #So basically what is being saved is accounts[cool-account-name] = {this-is-a-password:1}

所以在那之后我希望帐户功能发生这种情况。我希望它打印每个单独的项目,所以基本上它将打印以下每个:用户名,密码和UUID。因此提供上面的信息将打印用户名:cool-account-name,密码:这是一个密码,UUID:1。

2 个答案:

答案 0 :(得分:0)

您只需要在帐户[usernames]

的值上添加另一个循环
def accounts():
  for usernames in accounts:
    for passwords in accounts[usernames]:
      # Here you can access the UUID you want through: accounts[usernames][passwords]

答案 1 :(得分:0)

字典与列表的工作方式不同,因此您必须使用.values()或.keys()进行迭代。

accounts.keys()将返回字典中的所有键:

d = {1:2,3:4}

for v in d.keys():
    print (v)
# Would print 1 and 3

# And
for v in d.keys():
    print (d[v])
# Would print 2 and 4

accounts.values()将返回字典中这些键的所有值:

d = {1:2,3:4}

for v in d.values():
    print (v)
# Would print 2 and 4

您还必须在每个函数中添加global accounts行,以便它能够访问从外部定义的帐户变量。否则,每个函数都会创建自己的帐户变量或给出错误