Python – Set from dictionary values
Last Updated :
23 Apr, 2023
Given a dictionary, the task is to write a Python program to get all the values and convert to set.
Examples:
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 3, ‘best’ : 7, ‘for’ : 3, ‘geek’ : 4}
Output : {3, 4, 7}
Explanation : 2nd occurrence of 3 is removed in transformation phase.
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 3, ‘best’ : 7, ‘geek’ : 4}
Output : {3, 4, 7}
Explanation : 2nd occurrence of 4 is removed in transformation phase.
Method #1 : Using generator expression + {}
In this, we perform task of getting all the values using generator expression and {} operator performs task of removing duplicate elements and conversion to set.
Python3
test_dict = { 'Gfg' : 4 , 'is' : 3 , 'best' : 7 , 'for' : 3 , 'geek' : 4 }
print ( "The original dictionary is : " + str (test_dict))
res = {test_dict[sub] for sub in test_dict}
print ( "The converted set : " + str (res))
|
Output:
The original dictionary is : {‘Gfg’: 4, ‘is’: 3, ‘best’: 7, ‘for’: 3, ‘geek’: 4}
The converted set : {3, 4, 7}
Method #2 : Using values() + set()
In this, we perform task of getting values from dictionary using values() and set() is used to conversion to set.
Python3
test_dict = { 'Gfg' : 4 , 'is' : 3 , 'best' : 7 , 'for' : 3 , 'geek' : 4 }
print ( "The original dictionary is : " + str (test_dict))
res = set (test_dict.values())
print ( "The converted set : " + str (res))
|
Output:
The original dictionary is : {‘Gfg’: 4, ‘is’: 3, ‘best’: 7, ‘for’: 3, ‘geek’: 4}
The converted set : {3, 4, 7}
Method #3:Using Counter() function
Python3
from collections import Counter
test_dict = { 'Gfg' : 4 , 'is' : 3 , 'best' : 7 , 'for' : 3 , 'geek' : 4 }
print ( "The original dictionary is : " + str (test_dict))
freq = Counter(test_dict.values())
reslist = list (freq.keys())
res = set (reslist)
print ( "The converted set : " + str (res))
|
Output
The original dictionary is : {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
The converted set : {3, 4, 7}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using a loop to iterate over the dictionary values
Initialize an empty list called values_list.
Use a loop to iterate over the values of the dictionary test_dict.
Append each value to the values_list.
Convert the values_list to a set using the set() function and assign it to a variable called res.
Print the converted set res.
Python3
test_dict = { 'Gfg' : 4 , 'is' : 3 , 'best' : 7 , 'for' : 3 , 'geek' : 4 }
print ( "The original dictionary is : " + str (test_dict))
values_list = []
for val in test_dict.values():
values_list.append(val)
res = set (values_list)
print ( "The converted set : " + str (res))
|
Output
The original dictionary is : {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
The converted set : {3, 4, 7}
Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(n), where n is the number of values in the dictionary.
Share your thoughts in the comments
Please Login to comment...