How to Create a Dictionary in Python ( 3 Ways )

The dictionary (short form dict) is a fundamental data structure in Python. It uses key-value pairs to store the data in an efficient manner. Creating dictionary is a simple task in python however, we can use different ways to create a dictionary that fits our real data. 

In this article, we will learn three methods for creating a dictionary in Python. You will be able to make comparisons among these and select the appropriate method for your dataset.

Create a Dictionary Using {} Curly Brackets

This is a basic and intuitive way to create a dictionary in Python. We just need to enclose all the key-value pairs in the curly bracket separated by commas. Let’s take an example.

cities = {'Lahore': 'Pakistan', 'Tokyo': 'Japan', 'Sharjah': 'Dubai'}
print(cities)

Output

{'Lahore': 'Pakistan', 'Tokyo': 'Japan', 'Sharjah': 'Dubai'}

Dictionary is a mutable data structure, we don’t need to assign the data at the time of creating. We can just create an empty dictionary and update it later.

cities = {}
cities['Lahore'] = 'Pakistan'
cities['Tokyo'] = 'Japan'
cities['Sharjah'] = 'Dubai'
print(cities)

Output
{'Lahore': 'Pakistan', 'Tokyo': 'Japan', 'Sharjah': 'Dubai'}

This method is simple to implement but if we get a large dataset, then it involves a significant amount of typing work.

Create a Dictionary Using the Dict Function

If we have a list of key-value data, the dict function can convert it into a dictionary saving us from the manual entries. See the following example, we have a prepared list of data and feed it into the dict function to create the dictionary.

cities = [('Lahore', 'Pakistan'), ('Sharjah', 'Japan'), ('Sharjah', 'Dubai')]
result = dict(cities)
print(result)

Output

{'Lahore': 'Pakistan', 'Tokyo': 'Japan', 'Sharjah': 'Dubai'}

If the list does not contains key-value tuples, we can use dict.formkeys() method to create keys for the data in the list.

cities = ['Lahore', 'Karachi', 'Multan']
# every key will have value 'Pakistan'
result = dict.fromkeys(cities,'Pakistan')
print(result)

Output

{'Lahore': 'Pakistan', 'Tokyo': 'Japan', 'Sharjah': 'Dubai'}

If there are two lists, once contains the keys and the other contains values, we can make nice use of dict.fromkeys() function along with zip function. The zip function takes the iterators as its parameters and returns the zip object by pairing the first item of each iterator

cities_list = ['Lahore', 'Tokyo', 'Sharjah']
countries_list = ['Pakistan', 'Japan', 'Dubai']
result = dict(zip(cities_list, countries_list))
print(result)

Output

{'Lahore': 'Pakistan', 'Tokyo': 'Japan', 'Sharjah': 'Dubai'}

Create a Dictionary Using Dict Comprehension

If we want to build a dictionary by selecting specific items from the original data set, we can either do it manually by picking and typing the items into the dictionary or using some loop logic. Of course, we will prefer looping over the dataset to build a dictionary automatically.

Dict = {key: value for key,value in iterable (if condition)}

We have three components of the above dict template.

  • A for loop to iterate the iterables in input data
  • If condition (optional)
  • Key:Value expression to work with the items
cities_list = ['Lahpre', 'New York', 'Tokyo', 'Karachi', 'Islamabad']
countries_list = ['Pakistan', 'UK', 'Japan', 'Pakistan', 'Pakistan']
pak_cities = {city: country for city, country in zip(cities_list, countries_list) if country == 'Pakistan'}
print(pak_cities)

Output

{'Lahore': 'Pakistan', 'Karachi': 'Pakistan', 'Islamabad': 'Pakistan'}

In the above example, we created a dictionary using dict comprehension method containing cities only in Pakistan using few lines of code.

Dict comprehension allows the use of if statements, hence we have more flexibility to filter out data and create a custom dictionary. 

Wrapping up the article, we have learned three methods of creating a dictionary in python. It is not python is not limited to these functions, however, You can select any of these methods based on the scenario.

Gaelim Holland

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments