Python
Container Types
dict
create

Create a Python dictionary: explanation and examples

In this post, you'll learn the different ways to create a Python dictionary.

It will cover the following

  • From a list or tuple to dictionary
  • Creating a dictionary with a for loop
  • Creating nested dictionaries
  • Using dictionaries to create dictionaries and phone books
  • From dictionary to dataframe

1. Creating a dictionary in general

A dictionary in Python is a kind of collection with elements paired with keys and values. Dictionaries are mutable and cannot be used as an index, but you can use keys to reference values. Also, the key must be unique within the dictionary.

💡

For an at-a-glance comparison to other collection types, see this post.

The basic way to create a dictionary is to use curly braces {}, and keys and values are joined by a colon :.

Here's how to create an empty dictionary and a dictionary with values.

empty_dict_1 = {}
empty_dict_2 = dict()
 
my_dict = {"apple": 1, "banana": 2, "cherry": 3}

In the code above, "apple", "banana", and "cherry" represent keys, and 1, 2, and 3 represent values corresponding to each key.

2. Creating a dictionary from a list

Converting a list into a dictionary is very easy. You can use the zip() and dict() functions to convert a list of keys and values into a dictionary.

The zip() function concatenates the keys list and the values list into a tuple, and the dict() function converts this tuple into a dictionary. This creates a new dictionary combining the two lists.

keys = ["apple", "banana", "cherry"]
values = [1, 2, 3]
 
my_dict = dict(zip(keys, values))

3. Creating a dictionary from tuples

Like lists, tuples can be easily converted to dictionaries. To create a dictionary, the first element of the tuple is the key, and the second element is the value.

When you apply the dict() function to a tuple, each tuple is converted to a key-value pair in a dictionary, as shown below4.

tuples = (("apple", 1), ("banana", 2), ("cherry", 3))
 
my_dict = dict(tuples)

4. Creating a dictionary with a for loop

With dictionary comprehension, you can dynamically create a dictionary using a for loop.

For example, let's create a dictionary whose keys are the numbers 1 through 5 and whose values are the squares of those numbers.

squares = {i: i**2 for i in range(1, 6)}

5. Creating a nested dictionary (a dictionary within a dictionary)

You can also place another dictionary inside a dictionary (nested dictionary). This allows you to structure your data hierarchically.

In the example below, fruit and vegetable in the nested dictionary are the keys of the parent dictionary, and each value corresponding to those keys is another dictionary.

nested_dict = {
    "fruit": {"apple": 1, "banana": 2},
    "vegetable": {"carrot": 3, "pepper": 4}
}

6. Create a Eng-Kor dictionary with a dictionary

Dictionaries can also be used like real dictionaries. Here we'll create a simple English-Korean dictionary.

dictionary = {
    "apple": "사과",
    "banana": "바나나",
    "cherry": "체리"
}

In this code, the English words are used as keys and the Korean translations of the words are used as values.

7. Creating a phone book with a dictionary

You can also use a dictionary to create a simple phone book. You can use people's names as keys and their phone numbers as values.

phonebook = {
    "John": "010-1234-5678",
    "Jane": "010-9876-5432",
    "Mike": "010-1357-2468"
}

8. Creating a Data Frame with a Dictionary

A dataframe is a two-dimensional tabular data structure provided by the Pandas library. It has multiple columns, each of which can have a different type of value (int, float, str, etc.).

Dictionaries make it easy to create dataframes.

import pandas as pd
 
data = {
    "Name": ["John", "Anna", "Peter"],
    "Age": [28, 24, 33],
    "City": ["New York", "Paris", "Berlin"]
}
 
df = pd.DataFrame(data)
 
# Output
    Name  Age      City
0   John   28  New York
1   Anna   24     Paris
2  Peter   33    Berlin

In this code, each key is a column name in the dataframe, and the list associated with that key is the value of that column.

If you print the dataframe, you can see the column names ("Name", "Age", "City") and their corresponding values.

Conclusion

Dictionaries are very useful data structures in Python. They make it easy to store, retrieve, and manipulate data.

We hope that the different ways to create a Python dictionary in this article will help you in your real-world development.

copyright for Create a Python dictionary: explanation and examples

© 2023 All rights reserved.