简体   繁体   English

打印由用户输入生成的词典的内容

[英]Printing the contents of a dictionary generated by user input

Getting back into python again after starting and then stopping about a year ago. 在大约一年前开始然后停止之后再次回到python。 I was just messing with dictionaries and building them dynamically with user input and within a function. 我只是搞砸了字典,并通过用户输入和在函数中动态构建它们。

The code below works, but outputs it as the generic dictionary format, where what I'd like to do is have it output on a line by line basis with each key and value being on one line. 下面的代码有效,但是将其输出为通用词典格式,我想做的是逐行输出,每个键和值都在一行上。

def person_info(name, age, address, employer, phone):

    name = name.strip()
    age = age.strip()
    address = address.strip()
    employer = employer.strip()
    phone = phone.strip()

    full_info = {'Name:': name, 'Age': age, 'Address': address, 'Employer': employer, 'Phone': phone}
    return full_info

while True:
    name = input('Enter Name: ')
    age = input('Enter Age: ')
    address = input('Enter Address: ')
    employer = input('Enter Employer: ')
    phone = input('Enter Phone Number: ')

    if name == 'q' or age == 'q' or address == 'q' or employer == 'q' or phone == 'q':
        print("...quitting")
        break

    else:
        person = person_info(name, age, address, employer, phone)
        print(person)
        break

With this I get the output as: 这样我得到的输出为:

{'Name:': 'Tim', 'Age': '42', 'Address': '1111 Place Drive', 'Employer': 'Earth', 'Phone': '555'}

Where what I'd like is 我想在哪里

Name: Tim 姓名:蒂姆

Age: 42 年龄:42

etc... 等等...

I know that if I had the dictionary statically defined I could just use something like 我知道,如果我有静态定义的字典,我可以使用类似

for key, value in full_info.items():
    print(key, value)

And it will give me the output I want, but with the method I'm trying it doesn't seem to work. 它会给我想要的输出,但是用我尝试的方法似乎不起作用。 I'm not sure if this has to do with the dictionary being defined within the function. 我不确定这是否与函数中定义的字典有关。

I'm sure there's a super simple answer for this, but I haven't been able to find it thus far. 我敢肯定有一个超级简单的答案,但是到目前为止我还找不到。

Thanks! 谢谢!

Iterating through the dictionary's items seem to work, try this and tell me if it solves your problem 遍历字典中的项目似乎可行,尝试一下并告诉我它是否可以解决您的问题

def person_info(name, age, address, employer, phone):

    name = name.strip()
    age = age.strip()
    address = address.strip()
    employer = employer.strip()
    phone = phone.strip()

    full_info = {'Name:': name, 'Age:': age, 'Address:': address, 'Employer:': employer, 'Phone:': phone}
    return full_info

while True:
    name = input('Enter Name: ')
    age = input('Enter Age: ')
    address = input('Enter Address: ')
    employer = input('Enter Employer: ')
    phone = input('Enter Phone Number: ')

    if name == 'q' or age == 'q' or address == 'q' or employer == 'q' or phone == 'q':
        print("...quitting")
        break

    else:
        person = person_info(name, age, address, employer, phone)
        for key, value in person.items():
            print(key, value)

        break

Output seems to be in the format that you want using this 输出似乎是您要使用的格式

Let's see where those confusing prints are coming from. 让我们看看那些令人困惑的印刷品是从哪里来的。 First, I'll take your code, suppress your print(person) line. 首先,我将接受您的代码,取消您的print(person)行。 See what only the input() functions do: 查看仅input()函数的作用:

def person_info(name, age, address, employer, phone):

    name = name.strip()
    age = age.strip()
    address = address.strip()
    employer = employer.strip()
    phone = phone.strip()

    full_info = {'Name:': name, 'Age': age, 'Address': address, 'Employer': employer, 'Phone': phone}
    return full_info

while True:
    name = input('Enter Name: ')
    age = input('Enter Age: ')
    address = input('Enter Address: ')
    employer = input('Enter Employer: ')
    phone = input('Enter Phone Number: ')

    if name == 'q' or age == 'q' or address == 'q' or employer == 'q' or phone == 'q':
        print("...quitting")
        break

    else:
        person = person_info(name, age, address, employer, phone)
        # print(person) NOTICE: This is commented out for now.
        break

Here is the output of this version: 这是此版本的输出:

Enter Name: a

Enter Age: b

Enter Address: c

Enter Employer: d

Enter Phone Number: e

It just asks me, by printing to my screen, what name/age/address/employer/phone I want to enter. 它只是通过打印到我的屏幕上问我要输入什么名称/年龄/地址/雇主/电话。 When I type a/b/c/d/e, those are displayed on the screen as well, because I typed them. 当我键入a / b / c / d / e时,这些字符也会显示在屏幕上,因为我键入了它们。 No further print at all for this version. 此版本完全不再打印。

Now let's uncomment that print(person) line. 现在让我们取消对print(person)行的注释。 Now, in addition to what we just saw , the person must be printed. 现在, 除了我们刚才看到的以外 ,还必须打印此person So un-comment that, and run your code as is, you'll get this: 因此,取消注释,然后按原样运行代码,您将获得以下信息:

Enter Name: a

Enter Age: b

Enter Address: c

Enter Employer: d

Enter Phone Number: e
{'Name:': 'a', 'Age': 'b', 'Address': 'c', 'Employer': 'd', 'Phone': 'e'}

Notice, the only addition is the dictionary. 注意,唯一的补充是字典。 The first "Enter something" lines are exactly the same as before, solely due to you asking those input s. 第一行“输入内容”行与之前的行完全相同,完全是由于您询问了这些input s所致。 That's it. 而已。 It doesn't print anything more, or anything unexpected. 它不会再打印任何东西,也不会输出任何意外内容。

There is no way to hide those Enter Name: a / Enter Age: b prints. 无法隐藏那些Enter Name: a / Enter Age: b打印内容。 You can, however, edit the last dictionary. 但是,您可以编辑最后一个字典。 For that you just need to modify the print(person) into: 为此,您只需要将print(person)修改为:

for key, value in person.items(): print(key, value)

Now the output becomes: 现在输出变为:

Enter Name: a

Enter Age: b

Enter Address: c

Enter Employer: d

Enter Phone Number: e
Name: a
Age b
Address c
Employer d
Phone e

Again, the first 5 prints of Enter Name: a / Enter Age: b etc , and then your re-formatted person dictionary. 同样, Enter Name: a / Enter Age: b etc的前5张照片,然后重新格式化的person词典。 Again, nothing more is printed, nothing unexpected. 再说一次,什么也没印刷,没有什么意外的。

Hope this clarifies everything. 希望这可以澄清一切。

person_info function returns a dict. person_info函数返回一个字典。 When you invoke print, it will just print a dict in your case, as that is the default representation of dict that you can see by calling full_info.__str__() . 调用print时,它将仅打印您所用的字典,因为这是您可以通过调用full_info.__str__()看到的字典的默认表示形式。 You could have an alternative presentation by defining an additional function that is in charge of printing. 您可以通过定义一个负责打印的附加功能来进行替代显示。 Alternatively, wrap person_info into a class, then you can use print(person) , like here: 或者,将person_info包装到一个类中,然后可以使用print(person) ,如下所示:

在此处输入图片说明

It is not much more code, but it has added advantage, it guarantees order of printout and it makes usage simpler, no need to use for loop all over the place. 它不是更多的代码,但是它具有更多的优势,它可以确保打印输出的顺序,并且使使用更加简单,而无需在各处使用for循环。

In any case, others have already answered how you can do this, but here is a bit more detail. 无论如何,其他人已经回答了您如何执行此操作,但是这里有更多详细信息。 You can use function's output as an object to iterate over in the for loop, like this: 您可以使用函数的输出作为对象在for循环中进行迭代,如下所示:

在此处输入图片说明

Function returns a dict, and you can apply items method on it to iterate over it. 函数返回一个字典,您可以对其应用items方法以对其进行迭代。 Since you have been away from Python, notice that you can pass dict's values as arguments to function using unpacking * . 由于您远离Python,请注意,您可以使用拆包*将dict的值作为参数传递给函数。

Notice that dict does not guarantee the order. 请注意,dict不保证顺序。 So the output may not be predictable, like here: 因此输出可能无法预测,如下所示: 在此处输入图片说明

If you want the output to be guaranteed then use OrderedDict from collections import OrderedDict or class as mentioned above or define a printing function. 如果要保证输出然后使用OrderedDict from collections import OrderedDictclass如上所述或定义打印功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM