Python | Convert a set into dictionary
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()
# Python code to demonstrate # converting set into dictionary # using fromkeys() # initializing set ini_set = {1, 2, 3, 4, 5} # printing intialized 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)) |
chevron_right
filter_none
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
# Python code to demonstrate # converting set into dictionary # using dict comprehension # initializing set ini_set = {1, 2, 3, 4, 5} # printing intialized 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)) |
chevron_right
filter_none
Output:
initial string {1, 2, 3, 4, 5}
<class 'set'>
final list {1: 'Geek', 2: 'Geek', 3: 'Geek', 4: 'Geek', 5: 'Geek'}
<class 'dict'>
Recommended Posts:
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert string dictionary to dictionary
- Python | Convert two lists into a dictionary
- Python | Convert Tuples to Dictionary
- Python | Convert a list to dictionary
- Python | Convert dictionary object into string
- Python | Convert dictionary to list of tuples
- Python | Convert a list of Tuples into Dictionary
- Python | Convert list of tuples to dictionary value lists
- Python | Convert byteString key:value pair of dictionary to String
- Python | Convert key-value pair comma separated string into dictionary
- Python | Convert list of nested dictionary into Pandas dataframe
- Python Dictionary
- Python | Get key from value in Dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



