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'}
The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.
To convert Python Set to Dictionary, use the fromkeys() method. The fromkeys() is an inbuilt function that creates a new dictionary from the given items with a value provided by the user. Dictionary has a key-value data structure. So if we pass the keys as Set values, then we need to pass values on our own.
This reference object is called the “key,” while the data is the “value.” Dictionaries and sets are almost identical, except that sets do not actually contain values: a set is simply a collection of unique keys. As the name implies, sets are very useful for doing set operations.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With