简体   繁体   中英

How to print dictionary key if it exists and its value of lists in specified format?

I'm trying to figure out how to print a dictionary key (if it exists) and its value of lists in this format (some records have a "fourth string", "fifth string"), etc. :

    First Name
    2018-11-05 10:12:15
    First string
    Second string
    Third string

I tried to code it this way but it didn't work

name = {'First Name':['2018-11-05 10:12:15','First string', 'Second String', 
        'Third String']} 

 answer = input("Enter name: ")
            for k, v in name.items():
                if answer == k:
                    print(k, v)
                else:
                    break
                 

You can access the key directly and print the list this way to match your format:

if answer in name:
    print(answer)
    for item in name[answer]:
        print(item)

First you need to find the value for dictionary key, then you need to iterate through the array values:

answer = input("Enter name: ")
if answer in name:
    value = name[answer]
    for item in value:
        print (item)

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