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?
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 = " ")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With