Open In App

How to Initialize Dictionary in Python

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python dictionary, each key is unique and we can store different data types as values. The simplest and most efficient method to initialize a dictionary is using curly braces {}. This is the easiest and most common way to create a dictionary.

We can use curly braces '{} ' and separate the keys and values with : colon. Each key-value pair is separated by a comma.

Python
a = {"name": "John", "age": 25, "city": "New York"}

# Print the dictionary
print(a)

Output
{'name': 'John', 'age': 25, 'city': 'New York'}

Other methods we can use to initialise a dictionary are:

Using dict() Constructor

Another way to create a dictionary is by using the dict() constructor. This method is useful when you want to create a dictionary from a list of tuples or from keyword arguments.

Python
a = dict(name="Alice", age=30, city="Los Angeles")

# Print the dictionary
print(a)

Output
{'name': 'Alice', 'age': 30, 'city': 'Los Angeles'}

We can also use list of key-value tuples to initialize a dictionary.

Python
a = dict([("name", "Bob"), ("age", 35), ("city", "Chicago")])

# Print the dictionary
print(a)

Output
{'name': 'Bob', 'age': 35, 'city': 'Chicago'}

Using a Dictionary Comprehension

Dictionary comprehension is a more advanced method to create a dictionary, but it's still quite simple and powerful. It lets us create a dictionary by iterating over a sequence, such as a list or range.

Python
a = {x: x**2 for x in range(5)}

# Print the dictionary
print(a)

Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Using fromkeys() Method

If we want to create a dictionary with predefined keys and the same value for all keys, we can use the fromkeys() method.

Python
a = dict.fromkeys(["name", "age", "city"], "Unknown")

# Print the dictionary
print(a)

Output
{'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}

Next Article

Similar Reads