2014-09-28 58 views
0

所以我需要遍歷字典中的字典詞典。基本上我保存這樣的信息字典:在函數中循環使用值

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。所以提供上面的信息將打印用戶名:酷帳戶名,密碼:這是一個密碼,和UUID:1.

+0

請參閱[此問題](http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python)for類似的問題與循環字典 – fluidmotion 2014-09-28 01:48:08

回答

0

你只需要添加另一個循環的帳戶的值[用戶名]

def accounts(): 
    for usernames in accounts: 
    for passwords in accounts[usernames]: 
     # Here you can access the UUID you want through: accounts[usernames][passwords] 
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線在各功能,這樣它就可以訪問從外部定義的賬戶變量。否則,每個函數會創建自己的賬戶變量或給出錯誤