简体   繁体   中英

How to print every key and value from a dictionary when the value is a list?

I wrote this dictionary:

dict = {
    "Someone1": ['Random1', 'Random2', 'Random3'],
    "Someone2": ['Random1', 'Random2', 'Random3'],
    }

And I want to print it in a way that the output will be:

Someone1 Random1
Someone1 Random2
Someone1 Random3
Someone2 Random1

and etc.

I tried this:

for name in dict.keys():
    print(name, dict[name])

But the output is not what I wanted What can I do?

You need another nested loop to iterate over dict[name] . Also, you can simplify the code by iterating over keys and values (aka items ):

for name, herbs in dict.items():
    for herb in herbs:
        print(name, herb)

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