我有这个程序,它几乎是完美的,但我需要字典在不同的行上打印,如下:
Please enter a name (or just press enter to end the input): Tom
Please enter Tom's phone: 555-5555
Please enter a name (or just press enter to end the input): Sue
Please enter Sue's phone: 333-3333
Please enter a name (or just press enter to end the input): Ann
Please enter Ann's phone: 222-2222
Please enter a name (or just press enter to end the input):
Thank you.
Your phonebook contains the following entries:
Sue 333-3333
Tom 555-5555
Ann 222-2222
这是我的代码:
def main():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
number = input("Please enter number: ")
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name == '':
print("Thank You!")
print("Your phonebook contains the following entries:\n",phoneBook)
main()
答案 0 :(得分:2)
循环浏览电话簿中的条目并一次打印一次:
for name, number in phoneBook.items():
print ("%s %s" % (name, number))
答案 1 :(得分:1)
类似的东西:
strs = "\n".join( " ".join((name,num)) for name,num in phoneBook.items() )
print("Your phonebook contains the following entries:\n",strs)
答案 2 :(得分:1)
如果您不想自己编写代码,pprint
可能是一个选项:
import pprint
....
print("Your phonebook contains the following entries:\n")
pprint.pprint(phoneBook)
答案 3 :(得分:1)
您可以使用format()
让您的生活更轻松:
for i in phoneBook.iteritems():
print("{0} {1}".format(*i))
答案 4 :(得分:0)
my_dictionary = {}
while True:
name = str(input("Enter a name: "))
if name == "":
break
elif name in my_dictionary:
print "Phone Number: " + my_dictionary[name]
else:
phone_number = input("Enter this person's number: ")
my_dictionary[name] = phone_number
print my_dictionary