Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Convert a set into dictionary
Python provides lot of flexibility to handle different types of data structures. There may be a need when you have to convert one Data Structure to another for a better use or better analysis of the data. In this article we will see how to convert a Python set to a Python dictionary.
Using zip() and dict()
The dict() function can be used to take input parameters and convert them to a dictionary. We also use the zip() function to group the keys and values together which finally become the key-value pairs in the dictionary ?
Example
set_keys = {1, 2, 3, 4}
set_values = {'Mon', 'Tue', 'Wed', 'Thu'}
new_dict = dict(zip(set_keys, set_values))
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Thu', 2: 'Tue', 3: 'Wed', 4: 'Mon'}
<class 'dict'>
Note: Since sets are unordered, the pairing of keys and values may vary in different runs.
Using dict.fromkeys()
When we need a dictionary with different keys but the value of each key is same, we can use the dict.fromkeys() method as shown below ?
Example
set_keys = {1, 2, 3, 4}
new_dict = dict.fromkeys(set_keys, 'Mon')
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Mon', 2: 'Mon', 3: 'Mon', 4: 'Mon'}
<class 'dict'>
Using Dictionary Comprehension
We can use dictionary comprehension to create a dictionary from a set, which provides a more concise and Pythonic approach ?
Example
set_keys = {1, 2, 3, 4}
new_dict = {element: 'Tue' for element in set_keys}
print(new_dict)
print(type(new_dict))
Running the above code gives us the following result −
{1: 'Tue', 2: 'Tue', 3: 'Tue', 4: 'Tue'}
<class 'dict'>
Comparison
| Method | Use Case | Flexibility |
|---|---|---|
zip() + dict() |
Different values for keys | High |
dict.fromkeys() |
Same value for all keys | Medium |
| Dictionary comprehension | Custom logic for values | Very High |
Conclusion
Converting a set to a dictionary can be achieved using zip() with dict() for paired data, dict.fromkeys() for uniform values, or dictionary comprehension for custom logic. Choose the method based on your specific requirements and data structure needs.
