Open In App

Set from Dictionary Values - Python

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to extract unique values from a dictionary and convert them into a set. In Python, sets are unordered collections that automatically eliminate duplicates. The goal is to extract all the values from the dictionary and store them in a set.

For example, given a dictionary like d = {'A': 4, 'B': 3, 'C': 7, 'D': 4}, the goal is to retrieve all values from the dictionary and store them in a set, resulting in {3, 4, 7}.

Using values()

This method is considered the most efficient because the values() method of the dictionary returns a view object that directly gives access to the dictionary’s values. Converting this view to a set using the set() allows us to easily get all unique values without the need for additional iterations.

Python
d = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}

res = set(d.values())
print(res)

Output
{3, 4, 7}

Explanation:

  • d.values() returns a view of the dictionary’s values ([4, 3, 7, 3, 4]).
  • set() converts these values into a set and removing duplicates and resulting in {4, 3, 7}.

Using Set Comprehension

Set comprehension is another efficient method that involves iterating over the dictionary’s values and adding them to a set in a single line. This method is almost as efficient as set(d.values()) but requires an explicit iteration over the values, making it slightly less optimal for very large dictionaries.

Python
d = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}

res = {value for value in d.values()}
print(res)

Output
{3, 4, 7}

Explanation: set comprehension iterate over the dictionary’s values and directly create a set and removes duplicates.

Using map()

map() applies a given function (e.g., lambda x: x) to each element in the dictionary’s values and then converts the result into a set. It’s more complex than other methods but useful when transformations are needed before adding values to the set.

Python
d = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}

res = set(map(lambda x: x, d.values()))
print(res)

Output
{3, 4, 7}

Explanation:

  • d.values() retrieves the dictionary's values ([4, 3, 7, 3, 4]).
  • map() applies an identity lambda (lambda x: x) to each value and resulting in the same values.
  • set() removes duplicates, resulting in the set {4, 3, 7}.

Using for loop

Manually iterating over the dictionary’s values and adding them to a set is valid but less efficient than using built-in methods like set(d.values()) or set comprehension due to loop overhead.

Python
d = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
res = set()

for value in d.values():
    res.add(value)
print(res)

Output
{3, 4, 7}

Explanation:

  • for loop iterates over the values of the dictionary d using d.values().
  • For each value in the dictionary d it is added to the set res using the add() method.

Next Article
Practice Tags :

Similar Reads