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() 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 pair in the dictionary.
Example
list_keys = {1,2,3,4} list_values = {'Mon','Tue','Wed','Thu'} new_dict = dict(zip(list_keys, list_values)) print(new_dict) print(type(new_dict))
Output
Running the above code gives us the following result −
{1: 'Mon', 2: 'Tue', 3: 'Thu', 4: 'Wed'} <class 'dict'>
Using dict.fromkeys
When we need a dictionary with different keys but the value of each key is same, we can use this method as shown below.
Example
list_keys = {1,2,3,4} new_dict = dict.fromkeys(list_keys,'Mon') print(new_dict) print(type(new_dict))
Output
Running the above code gives us the following result −
{1: 'Mon', 2: 'Mon', 3: 'Mon', 4: 'Mon'} <class 'dict'>
Using Dictionary Comprehension
We use a similar method as the previous approach except that in this case we have dictionary comprehension.
Example
list_keys = {1,2,3,4} new_dict = {element:'Tue' for element in list_keys} print(new_dict) print(type(new_dict))
Output
Running the above code gives us the following result −
{1: 'Tue', 2: 'Tue', 3: 'Tue', 4: 'Tue'} <class 'dict'>