Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
user_user Avatar asked Feb 10 '23 04:02

user_user


2 Answers

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 = " ")
like image 183
Simon Gibbons Avatar answered Feb 13 '23 11:02

Simon Gibbons


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)
like image 27
Noufal Ibrahim Avatar answered Feb 13 '23 12:02

Noufal Ibrahim