Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}
like image 252
Zach Avatar asked Dec 01 '14 23:12

Zach


People also ask

Can a dictionary key be a set?

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.

How do you make a dictionary a 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.

Can dictionaries have sets as values?

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.


1 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}
like image 176
wim Avatar answered Sep 26 '22 23:09

wim