Skip to content
Advertisement

Print dictionary with multiple values seperated

I have a dictioanry that has a key with more than one value:

{'bob': {"flying pigs"}, 'sam':{"open house", "monster dog"}, 'sally':{"glad smile"}}

I would like the dictionary on output to look like:

bob, flying pigs
sam, open house
sam, monster dog
sally, glad smile

My biggest struggle is to get the sam key to print the values on their own line.

Advertisement

Answer

you can use 2 for loops to first iterate on keys and value (dictionary) and the 2nd one to iterate on the set (dictionary values).

mydict = {'bob': {"flying pigs"}, 'sam':{"open house", "monster dog"}, 'sally':{"glad smile"}}

for key, value in mydict.items():
    for item in value:
        print(key, item, sep=', ')

Output:

bob, flying pigs
sam, open house
sam, monster dog
sally, glad smile
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement