Convert a set into dictionary
Sometimes we have to convert one data structure to another for various operations and issues in our daily coding and web development. As we may want to get a dictionary from the given set items. Let’s discuss some methods to convert a given set in a dictionary.
Convert Python Set to Dictionary
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.
Syntax
dictionary.fromkeys
(keys, value)
Parameters
The keys parameter is required, and it is an iterable specifying the keys of the new dictionary.
Set to Dict Using fromkeys()
# 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}final list {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
Set to Dict Using dict comprehension
# 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}final list {1: ’Geek’, 2: ’Geek’, 3: ’Geek’, 4: ’Geek’, 5: ’Geek’}
Set to dict Python
StackOverflow question
is there any pythonic way to convert a set into a dict?
I got the following set
s = {1,2,4,5,6}
and want the following dict
c = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
with a list you would do
a = [1,2,3,4,5,6]
b = []
while len(b) < len(a):
b.append(0)
c = dict(itertools.izip(a,b))
Answer
Use dict.fromkeys()
:
c = dict.fromkeys(s, 0)
Demo:
>>> s = {1,2,4,5,6}
>>> dict.fromkeys(s, 0)
{1: 0, 2: 0, 4: 0, 5: 0, 6: 0}
This works for lists as well; it is the most efficient method to create a dictionary from a sequence. Note all values are references to that one default you passed into dict.fromkeys()
, so be careful when that default value is a mutable object.
Archived version
Let’s discuss several ways to convert this set into a dictionary.
Method # 1: Using fromkeys()
|
Exit :
initial string {1, 2, 3, 4, 5} "class ’set’ & gt ; final list {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} "class ’dict’"
Method # 2: Using Dictation
|
Output:
initial string {1, 2, 3, 4, 5} "class ’set’" final list {1: ’Geek’, 2:’ Geek’, 3: ’Geek’, 4:’ Geek’, 5: ’Geek’} "class’ dict’"