简体   繁体   中英

Printing the contents of a dictionary generated by user input

Getting back into python again after starting and then stopping about a year ago. 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

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. See what only the input() functions do:

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. No further print at all for this version.

Now let's uncomment that print(person) line. Now, in addition to what we just saw , the person must be printed. 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. 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. You can, however, edit the last dictionary. For that you just need to modify the print(person) into:

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. Again, nothing more is printed, nothing unexpected.

Hope this clarifies everything.

person_info function returns a dict. 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__() . 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:

在此处输入图片说明

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.

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:

在此处输入图片说明

Function returns a dict, and you can apply items method on it to iterate over it. Since you have been away from Python, notice that you can pass dict's values as arguments to function using unpacking * .

Notice that dict does not guarantee the order. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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