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.
CodePudding user response:
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.
CodePudding user response:
Try something like:
def viewcontacts(contacts):
print("-------- view contacts --------")
for index (key, value) in enumerate(contacts.items()):
print (f"{index} {key} {value}")
CodePudding user response:
did i answer your question?
def viewcontacts(contacts):
index=0
print("-------- view contacts --------")
for key, value in contacts.items():
print (index," " ,key," ",value)
index =1
CodePudding user response:
Try to use another counter element in your for loop, which will be in a range on length of your dictionary.
def viewcontacts(contacts):
print("-------- view contacts --------")
for (key, value), id in contacts.items(), range(1, len(contacts)):
print (f" {id} {key} {value}")
or with enumerate function:
def viewcontacts(contacts):
print("-------- view contacts --------")
for (key, value), id in contacts.items(), enumerate(contacts):
print (f" {id} {key} {value}")