0

so I need to loop through dictionaries of dictionaries in dictionaries. Basically I am saving information like this to a dictionary:

accounts = {}

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

Then in another function I want to loop through all of these values, so for example this is what I have so far. This correctly loops through all of the newusernames.

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

Please help me, I just want a simple answer on how to loop through all of the values. Thank You!

EDIT So basically this is a example:

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}

So after that happens I want this to happen with the accounts function. I want it to print each separate item, so basically it would print each of the follow: username, password, and UUID. So supplied with the information above it would print Username: cool-account-name, Password: this-is-a-password, and the UUID: 1.

Michael Jones
  • 35
  • 1
  • 1
  • 6
  • See [this question](http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python) for similar issue with looping over dict – fluidmotion Sep 28 '14 at 01:48

2 Answers2

0

You just need to add another loop over the values of accounts[usernames]

def accounts():
  for usernames in accounts:
    for passwords in accounts[usernames]:
      # Here you can access the UUID you want through: accounts[usernames][passwords]
Eliran
  • 134
  • 4
0

Dictionaries work differently than lists, so you will have to use the .values() or .keys() to iterate.

accounts.keys() would return all the keys in a dictionary:

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() would return all the values of those keys in a dictionary:

d = {1:2,3:4}

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

You also must put global accounts line in each function, so that it would be able to access the accounts variable defined from outside. Otherwise, each function would create its own accounts variable or give an error

Electron
  • 308
  • 4
  • 13