Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to print out a dictionary with index numbers

Hiya I am trying to print out a dictionary so it ends up looking like this

-------- view contacts --------
    1    Stish        123
    2    Rita         321

I have got so far as to print it like this

-------- view contacts --------
        Stish        123
        Rita        321

But I am unsure as to how I could get it to print with index numbers as well. This is the code I have currently.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def viewcontacts(contacts):
    print("-------- view contacts --------") 
    for key, value in contacts.items():
        print ("       ",key,"      ",value)

many thanks for the help and please bear with me as I’m pretty inexperienced.

Tried to integrate a for loop with then x+1 for each value but I kept running into concatenation errors as its a string and not an integer that the dictionary values are being stored as.

>Solution :

This will do what you want:

def viewcontacts(contacts):
    print("-------- view contacts --------")
    for ix, (key, value) in enumerate(contacts.items()):
        print("{:3}    {:10}  {:8}".format(ix+1, key, value))

This produces the following:

-------- view contacts --------
  1    Stish            123
  2    Rita             321

This uses a fixed width for each field so that they line up properly.
You can adjust the field widths as needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading