How do you turn something into a dictionary in Python?

Dictionaries in Python store the data in form of key-value pairs where the keys should be unique and immutable. Whereas Sets in Python are used to store a list of unique values inside a single variable. Often there is a need to convert the Set into a Dictionary for a variety of reasons.

For example, consider an e-commerce website that stores various sets of items. We can convert these items into a key-value pair format where keys represent items and values represent their no of units, cost price, etc. Thus in this tutorial, we will learn how to convert a set into a dictionary in Python.

Some of the advantages of using Dictionary overs Sets are:

  1. It improves the readability of the code
  2. It helps in increasing the speed as we only have to look up the keys to getting their corresponding values instead of going over the entire set and searching for the keys and values
  3. It helps in faster analysis of data as the values provide extra information about their corresponding keys

Implementing List comprehension to convert Set to Dictionary in Python

A list comprehension contains a for loop that iterates over each element and executes an expression for that element.

In the below-mentioned example, we define a product_Set that stores a set of product names. We will convert this set into a dictionary by converting it into a key-value pair format. Here the key represents the product name and value is its associated cost. So we create a list comprehension which will use a for loop to iterate over each product in the product set. For each product, we will then associate it with its corresponding cost.

product_set = {'Toys', 'Clothes', 'Books', 'Kitchenware'}
print(f"The products set is:{product_set}")

avg_cost=[200,300,500,250]
for cost in avg_cost:
    dictionary = {product:cost  for product in product_set}

print(dictionary)
print(type(dictionary))

Output:

The products set is:{'Toys', 'Kitchenware', 'Clothes', 'Books'}
{'Toys': 250, 'Kitchenware': 250, 'Clothes': 250, 'Books': 250}
<class 'dict'>

Implementing fromkeys() to convert Set to Dictionary

The fromkeys() function in Python is used to generate a dictionary from the specified keys and values as the arguments. The syntax of the fromkeys() function is: fromkeys (key,value). The keys can represent any data structure such as a list or set etc which contains keys. Therefore in the below-mentioned code, the keys take the entire product_set as an input. The values represent the cost associated with each product name from the avg_cost set. Thus we successfully generate a dictionary from the product set.

product_set = {'Toys', 'Clothes', 'Books', 'Kitchenware'}
print(f"The products set is:{product_set}")

avg_cost=[200,300,500,250]
for cost in avg_cost:
    dictionary = dict.fromkeys(product_set,cost)

print(dictionary)
print(type(dictionary))

Output:

The products set is:{'Books', 'Clothes', 'Kitchenware', 'Toys'}
{'Books': 250, 'Clothes': 250, 'Kitchenware': 250, 'Toys': 250}
<class 'dict'>

Implementing zip and dict to convert Set to Dictionary

The zip() function in python takes a data structure or iterable such as a list or set as an argument and returns a zip object. The zip object maps the first item of each iterable together and continues this mapping till all the items have been mapped together. The dict() function is used to convert an iterable into a Python Dictionary. In the below-mentioned example, we initially give two sets (product_set and avg_cost) as an input to the zip() function. This function will map each product name to its corresponding cost and return a zip object. Then we convert this zip object to a Dictionary using the dict() function.

product_set = {'Toys', 'Clothes', 'Books', 'Kitchenware'}
print(f"The products set is:{product_set}")

avg_cost=[200,300,500,250]

dictionary = dict(zip(product_set,avg_cost))

print(dictionary)
print(type(dictionary))

Output:

The products set is:{'Clothes', 'Books', 'Kitchenware', 'Toys'}
{'Clothes': 200, 'Books': 300, 'Kitchenware': 500, 'Toys': 250}
<class 'dict'>

Thus we have reached the end of this tutorial on how to convert Set to Dictionary in Python. To read more about the sets in Python refer to the following mentioned links:

Python dictionary is an ordered collection (starting from Python 3.7) of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.

Let's see an example,

If we want to store information about countries and their capitals, we can create a dictionary with country names as keys and capitals as values.

KeysValuesNepalKathmanduItalyRomeEnglandLondon


Create a dictionary in Python

Here's how we can create a dictionary in Python.

capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}
print(capital_city)

Output

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

In the above example, we have created a dictionary named capital_city. Here,

  1. Keys are
    # dictionary with keys and values of different data types
    numbers = {1: "One", 2: "Two", 3: "Three"}
    print(numbers)
    0,
    # dictionary with keys and values of different data types
    numbers = {1: "One", 2: "Two", 3: "Three"}
    print(numbers)
    1,
    # dictionary with keys and values of different data types
    numbers = {1: "One", 2: "Two", 3: "Three"}
    print(numbers)
    2
  2. Values are
    # dictionary with keys and values of different data types
    numbers = {1: "One", 2: "Two", 3: "Three"}
    print(numbers)
    3,
    # dictionary with keys and values of different data types
    numbers = {1: "One", 2: "Two", 3: "Three"}
    print(numbers)
    4,
    # dictionary with keys and values of different data types
    numbers = {1: "One", 2: "Two", 3: "Three"}
    print(numbers)
    5

Note: Here, keys and values both are of string type. We can also have keys and values of different data types.


Example 1: Python Dictionary

# dictionary with keys and values of different data types
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)

Output

[3: "Three", 1: "One", 2: "Two"]

In the above example, we have created a dictionary named numbers. Here, keys are of integer type and values are of string type.


Add Elements to a Python Dictionary

We can add elements to a dictionary using the name of the dictionary with

# dictionary with keys and values of different data types
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)
6. For example,

capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)

Output

Initial Dictionary:  {'Nepal': 'Kathmandu', 'England': 'London'}
Updated Dictionary:  {'Nepal': 'Kathmandu', 'England': 'London', 'Japan': 'Tokyo'}

In the above example, we have created a dictionary named capital_city. Notice the line,

capital_city["Japan"] = "Tokyo"

Here, we have added a new element to capital_city with key:

# dictionary with keys and values of different data types
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)
7 and value:
# dictionary with keys and values of different data types
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)
8.


Change Value of Dictionary

We can also use

# dictionary with keys and values of different data types
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)
6 to change the value associated with a particular key. For example,

student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
print("Initial Dictionary: ", student_id)

student_id[112] = "Stan"

print("Updated Dictionary: ", student_id)

Output

Initial Dictionary:  {111: 'Eric', 112: 'Kyle', 113: 'Butters'}
Updated Dictionary:  {111: 'Eric', 112: 'Stan', 113: 'Butters'}

In the above example, we have created a dictionary named student_id. Initially, the value associated with the key

[3: "Three", 1: "One", 2: "Two"]
0 is
[3: "Three", 1: "One", 2: "Two"]
1. Now, notice the line,

student_id[112] = "Stan"

Here, we have changed the value associated with the key

[3: "Three", 1: "One", 2: "Two"]
0 to
[3: "Three", 1: "One", 2: "Two"]
3.


Accessing Elements from Dictionary

In Python, we use the keys to access their corresponding values. For example,

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
0

Here, we have used the keys to access their corresponding values.

If we try to access the value of a key that doesn't exist, we'll get an error. For example,

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
1

Removing elements from Dictionary

We use the

[3: "Three", 1: "One", 2: "Two"]
4 statement to remove an element from the dictionary. For example,

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
2

Output

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
3

Here, we have created a dictionary named student_id. Notice the code,

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
4

The

[3: "Three", 1: "One", 2: "Two"]
4 statement removes the element associated with the key
[3: "Three", 1: "One", 2: "Two"]
6.

We can also delete the whole dictionary using the

[3: "Three", 1: "One", 2: "Two"]
4 statement,

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
5

We are getting an error message because we have deleted the student_id dictionary and student_id doesn't exist anymore.


Python Dictionary Methods

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

FunctionDescriptionall()Return

[3: "Three", 1: "One", 2: "Two"]
8 if all keys of the dictionary are True (or if the dictionary is empty).any()Return
[3: "Three", 1: "One", 2: "Two"]
8 if any key of the dictionary is true. If the dictionary is empty, return
capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)
0.len()Return the length (the number of items) in the dictionary.sorted()Return a new sorted list of keys in the dictionary.clear()Removes all items from the dictionary.keys()Returns a new object of the dictionary's keys.values()Returns a new object of the dictionary's values


Dictionary Membership Test

We can test if a

capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)
1 is in a dictionary or not using the keyword
capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)
2. Notice that the membership test is only for the
capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)
3 and not for the
capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)
4.

How to convert into dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How to convert a string into dictionary?

Method 1: Splitting a string to generate a key: value pair of the dictionary In this approach, the given string will be analyzed and with the use of the split() method, the string will be split in such a way that it generates the key: value pair for the creation of a dictionary.

How to convert string object to dictionary in Python?

Using ast..
#convert string to dictionary..
#using ast().
import ast..
#initialising the string..
string_1 = '{"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"}'.
print("String_1 is ",string_1).
#using ast.literal_eval..
res_dict=ast.literal_eval(string_1).

Can you use an object as a dictionary key?

Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.