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.
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.