Change language

Python convert Set to Dict

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()

# Python code for demonstration
# convert the set to a dictionary
# using fromkeys ()

  
# initialization set

ini_set = { 1 , 2 , 3 , 4 , 5 }

 
# printing the initialized set

print ( "initial string" , ini_set)

print ( type (ini_set))

 
# Convert the set to a dictionary

res = dict . fromkeys (ini_set, 0 )

 
# print the final result and its type

print ( " final list " , res)

print ( type (res))

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

# Python code for demonstration
# converting the set to a dictionary
# using dictation

 

  
# initialization set

ini_set = { 1 , 2 , 3 , 4 , 5 }

 
# print the initialized set

print ( "initial string" , ini_set)

print ( type (ini_set))

 

str = ’fg’

# Convert set to dict

res = {element: ’Geek’ + str for element in ini_set}

 
# print the 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: ’Geek’, 2:’ Geek’, 3: ’Geek’, 4:’ Geek’, 5: ’Geek’} "class’ dict’" 

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically