Making a Set from Dictionary Values

Making a Set from Dictionary Values

I want to create a set from the values of an existing dict

def function(dictionary):
    ... 
    return set_of_values

Say my dictionary looks like this: {'1': 'Monday', '2': 'Tuesday', '3': 'Monday'}

I want a set returned that only contains the unique values, like this:

{'Monday', 'Tuesday'}

2 Answers

For Python:

set(d.values())

Equivalent on Python 2.7:

set(d.viewvalues())

If you need a cross-compatible Python 2.7/3.x code:

{d[k] for k in d}
9

Just another way to unique out:

 >>> my_dict = {'1': 'Monday', '3': 'Monday', '2': 'Tuesday'}
 >>> {y:x for x,y in my_dict.iteritems()}.keys()
 ['Tuesday', 'Monday']
 >>>
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.