How to nicely print a dictionary that has a list as the value and a String for a key [PYTHON]


Basically, I would like to print a phone book and I am having a hard time printing all the info, I wanted it to look like this:

Name                       Company                           Phone Number
Name 1                     Company 1                         Number 1
Name 2                     Company 2                         Number 2
Name 2                     Company 2                         Number 2
book = {"Name 1": ["Company 1", "Company 1"], "Name 2": ["Company 2", "Company 2"], "Name 3": ["Company 3", "Company 3"]}

but when I am printing it, the values are coming out looking like a list instead of separately
I thought about using pprint, but I am not so sure on how to do that with pprint either. Is there anyway I could maybe do this with a for loop?

Asked By: joazeiro



You can try something like this:

dict1 = {"Name 1": ["Company 1","Number 1"], "Name 2": ["Company 2", "Number 2"], "Name 3": ["Company 3", "Number 3"]}

# Print the names of the columns.
print("{:<10} {:<10} {:<10}".format('NAME', 'COMPANY', 'PHONE NUMBER'))

# print each data item.
for key, value in dict1.items():
    company, number = value
    print("{:<10} {:<10} {:<10}".format(key, company, number))


Name1      Company1   Number1   
Name2      Company2   Number3   
Name3      Company2   Number3   
Answered By: Saif Baig
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.