1

我有这个程序,它几乎是完美的,但我需要将字典打印在单独的行上,如下所示:

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()
4

5 回答 5

2

遍历电话簿中的条目并一次打印一个:

for name, number in phoneBook.items():
    print ("%s %s" % (name, number))
于 2013-04-29T02:48:32.973 回答
1

像这样的东西:

strs = "\n".join( " ".join((name,num)) for name,num in phoneBook.items() )
print("Your phonebook contains the following entries:\n",strs)
于 2013-04-29T02:59:55.827 回答
1

您可以使用format()以下方法让您的生活更轻松:

for i in phoneBook.iteritems():
    print("{0} {1}".format(*i))
于 2013-04-29T04:27:47.657 回答
1

如果您不想自己编写代码,pprint可以选择:

import pprint

....

print("Your phonebook contains the following entries:\n")
pprint.pprint(phoneBook)
于 2013-04-29T03:42:28.143 回答
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
于 2020-03-16T04:32:32.360 回答