The Wayback Machine - https://web.archive.org/web/20240204103948/https://www.geeksforgeeks.org/python-convert-a-set-into-dictionary/
Open In App
Related Articles

Python | Convert a set into dictionary

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes we need to convert one data structure into another for various operations and problems in our day to day coding and web development. Like we may want to get a dictionary from the given set elements.
Let’s discuss a few methods to convert given set into a dictionary.

Method #1: Using fromkeys() 

Python3




# Python code to demonstrate
# converting set into dictionary
# using fromkeys()
 
# initializing set
ini_set = {1, 2, 3, 4, 5}
 
# printing initialized set
print ("initial string", ini_set)
print (type(ini_set))
 
# Converting set to dictionary
res = dict.fromkeys(ini_set, 0)
 
# printing final result and its type
print ("final list", res)
print (type(res))


Output: 

initial string {1, 2, 3, 4, 5}
<class 'set'>
final list {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
<class 'dict'>

 

Method #2: Using dict comprehension 

Python3




# Python code to demonstrate
# converting set into dictionary
# using dict comprehension
 
 
# initializing set
ini_set = {1, 2, 3, 4, 5}
 
# printing initialized set
print ("initial string", ini_set)
print (type(ini_set))
 
str = 'fg'
# Converting set to dict
res = {element:'Geek'+str for element in ini_set}
 
# printing final result and its type
print ("final list", res)
print (type(res))


Output

initial string {1, 2, 3, 4, 5}
<class 'set'>
final list {1: 'Geekfg', 2: 'Geekfg', 3: 'Geekfg', 4: 'Geekfg', 5: 'Geekfg'}
<class 'dict'>

Using the zip() function:

Approach:

Use the zip() function to create a list of keys and a list of default values.
Use a dictionary comprehension to create a dictionary from the two lists.

Python3




def set_to_dict(s):
    keys = list(s)
    values = [None] * len(s)
    return {k: v for k, v in zip(keys, values)}
 
s = {1, 2, 3}
print(set_to_dict(s))


Output

{1: None, 2: None, 3: None}

Time complexity: O(n)
Space complexity: O(n)

 


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.


Last Updated : 24 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials