user_user
user_user

Reputation: 41

Python: Iterating through dictionaries within dictionaries

I have this test dictionary:

addressBook = {'a' : {'Name' : 'b', 'Address' : 'c', 'PhoneNo' : '5'}, 'd' : {'Name' : 'e', 'Address' : 'f', 'PhoneNo' : '7'}}

I want to iterate through each dictionary within addressBook and display each value (name, address and phoneno).

I have tried this:

for x in addressBook:
    for y in x:
        print(y, "\t", end = " ")

However, this only prints the key of each dictionary (i.e. 'a' and 'b').

How do I display all the values?

Upvotes: 4

Views: 1304

Answers (4)

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

Iterating over a dictionary only gives you the dictionary keys, not the values. If you want just the values, then use this:

for x in addressBook.values()

Alternatively, if you want both keys and values, use iteritems() like this:

for key,value in addressBook.iteritems():
        print key, value

Upvotes: 1

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72745

I would do something like this

for k1,d in addressBook.items:
   for k2,v2 in d.items:
      print("{} :: {}".format(k2, v2))

However if all you want is to print the dictionary neatly, I'd recommend this

   import pprint
   s = pprint.pformat(addressBook)
   print(s)

Upvotes: 3

Vivek Sable
Vivek Sable

Reputation: 10213

Issue with your code:

for x in addressBook:  # x is key from the addressBook dictionary.
    #- x is key and type of x is string. 
    for y in x:       # Now we iterate every character from the string.
        print(y, "\t", end = " ")  # y character is print

Try following:

for i in addressBook:
    print "Name:%s\tAddress:%s\tPhone:%s"%(addressBook[i]["Name"], addressBook[i]["Address"], addressBook[i]["PhoneNo"])


Name:b  Address:c   Phone:5
Name:e  Address:f   Phone:7

Upvotes: 1

Simon Gibbons
Simon Gibbons

Reputation: 7184

Whenever you iterate through a dictionary by default python only iterates though the keys in the dictionary.

You need to use either the itervalues method to iterate through the values in a dictionary, or the iteritems method to iterate through the (key, value) pairs stored in that dictionary.

Try this instead:

for x in addressBook.itervalues():
    for key, value in x.iteritems():
        print((key, value), "\t", end = " ")

Upvotes: 3

Related Questions