gdm
gdm

Reputation: 71

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.

Upvotes: 1

Views: 1176

Answers (1)

Vishal Singh
Vishal Singh

Reputation: 6234

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

Upvotes: 3

Related Questions