What is a Dictionary in Python?
A dictionary in Python is a mutable, unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. Keys within a dictionary must be unique and are used to access corresponding values. Here’s why dictionaries are favored in Python:
- Fast Access: Retrieval of data is swift because dictionaries use hashing, allowing for nearly instantaneous access to a value based on its key.
- Flexibility: They can store any type of object as values, providing great flexibility in organizing complex data structures.
- Dynamic Modifications: Dictionaries can be expanded or shrunk on the fly as they are mutable, meaning you can add or remove items after creation without creating a new dictionary.
How to Create a Dictionary
We can create a Dictionary using several methods. Let’s talk about them :
Using Curly Braces
You can create a dictionary directly using curly braces with key-value pairs.
student = {
'name': 'Akash Tyagi',
'age': 21,
'course': 'Computer Science'
}
Using the dict() Constructor
The dict() constructor allows you to create dictionaries from sequences of key-value pairs or keyword arguments.
# Using keyword arguments
student = dict(name='Harsh Singh', age=21, course='Computer Science')
# Using sequence of tuples
student = dict([('name', 'Harsh Singh'), ('age', 21), ('course', 'Computer Science')])
Dictionary Example
Let's consider an example where we manage a catalog of books in a library. Each book is represented as a dictionary with details such as title, author, and ISBN. Here’s how we might set it up:
Python
# Creating a dictionary to store book information
library_catalog = {
'001': {'title': 'Python Programming', 'author': 'Ravi', 'ISBN': '978-1-4302-6036-9'},
'002': {'title': 'Learn JavaScript', 'author': 'Sinki', 'ISBN': '978-1-4920-0876-0'},
'003': {'title': 'Data Structures & Algorithms', 'author': 'Mehak', 'ISBN': '978-1-4919-1889-1'}
}
# Accessing book information by its ID
book_id = '002'
book_info = library_catalog[book_id]
print(f"Book Title: {book_info['title']}, Author: {book_info['author']}, ISBN: {book_info['ISBN']}")

You can also try this code with Online Python Compiler
Run Code
Output
Book Title: Learn JavaScript, Author: Sinki, ISBN: 978-1-4920-0876-0
Note : This example shows how dictionaries can be used to group related information and access it conveniently using keys. This is just a basic illustration; dictionaries can be nested and combined in various ways to handle more complex data structures( which we will discuss later in this article).
Different Ways to Create a Python Dictionary
Here are some of the methods you can use to create dictionaries, each suitable for different scenarios:
Using dict() with Keyword Arguments
As previously mentioned, you can create a dictionary using keyword arguments where keys are provided as parameter names.
employee = dict(name="Nikunj", age=30, department="HR")
From a List of Tuples
You can convert a list of tuples, where each tuple consists of two elements (key and value), into a dictionary.
items = [('name', 'Nikunj'), ('age', 30), ('department', 'HR')]
employee = dict(items)
Using Dictionary Comprehensions
This method uses a similar syntax to list comprehensions and is efficient for creating dictionaries dynamically.
keys = ['name', 'age', 'department']
values = ['Nikunj', 30, 'HR']
employee = {k: v for k, v in zip(keys, values)}
Using fromkeys()
This method is used to create a new dictionary with keys from a given sequence and a uniform value for all keys.
keys = ['name', 'age', 'department']
default_value = None
employee = dict.fromkeys(keys, default_value)
Updating an Existing Dictionary
You can start with an empty dictionary and update it by adding new key-value pairs.
employee = {}
employee['name'] = 'Nikunj'
employee['age'] = 30
employee['department'] = 'HR'
Nested Dictionaries
Nested dictionaries are a way to store hierarchical or structured information in a Python dictionary. This involves placing a dictionary within another dictionary. Nested dictionaries are particularly useful for managing complex data relationships in a clear and scalable manner.
Here's an example of how you can structure and manipulate nested dictionaries:
Python
# A nested dictionary to represent a university's system
university = {
'Engineering': {
'Computer Science': {
'students': 300,
'faculty': 25
},
'Electrical': {
'students': 200,
'faculty': 20
}
},
'Arts': {
'History': {
'students': 150,
'faculty': 15
},
'Literature': {
'students': 180,
'faculty': 18
}
}
}
# Accessing nested information
num_cs_students = university['Engineering']['Computer Science']['students']
print(f"Number of Computer Science students: {num_cs_students}")
# Modifying nested information
university['Engineering']['Computer Science']['students'] = 320
print(f"Updated number of Computer Science students: {university['Engineering']['Computer Science']['students']}")

You can also try this code with Online Python Compiler
Run Code
Output
Number of Computer Science students: 300
Updated number of Computer Science students: 320
This example illustrates how nested dictionaries can be used to manage more detailed and structured data effectively, making them an excellent choice for more complex data management tasks such as handling data for different departments within a university.
Adding Elements to a Dictionary
Adding elements to a Python dictionary is straightforward and can be done in several ways, depending on the situation. Here’s how you can add new key-value pairs to an existing dictionary:
Direct Assignment
You can add a new element by assigning a value to a new key directly.
Python
student_info = {'name': 'Gaurav', 'age': 22}
student_info['major'] = 'Computer Science' # Adding a new key-value pair
print(student_info)

You can also try this code with Online Python Compiler
Run Code
Outputs
{'name': 'Gaurav', 'age': 22, 'major': 'Computer Science'}
Using the update() Method
The update() method allows you to add multiple key-value pairs at once. It is especially useful when merging two dictionaries or adding a large number of elements.
new_data = {'grade': 'A', 'graduation_year': 2022}
student_info.update(new_data)
print(student_info)
Accessing Elements of a Dictionary
Accessing elements in a Python dictionary is an essential skill, as it allows you to retrieve specific values based on their keys. Here's how to do it:
Using Square Brackets:
The most direct method is to use the key inside square brackets. If the key is not present, Python will raise a KeyError.
Python
student_info = {'name': 'Rekha', 'age': 22, 'major': 'Computer Science'}
print(student_info['name'])

You can also try this code with Online Python Compiler
Run Code
Outputs:
Rekha
Using the get() Method
The get() method provides a safer way to access values. It allows you to specify a default value if the key is not found, preventing a KeyError.
print(student_info.get('name', 'Not Available'))
print(student_info.get('height', 'Not Available'))
Outputs:
Rekha
Not Available
Access a Value in Python Dictionary
Accessing a specific value in a Python dictionary is a straightforward operation. It involves using the key to retrieve the corresponding value, similar to looking up a word in a physical dictionary to find its definition. Here’s how you can access a value using a key:
Python
# Example dictionary of student grades
grades = {
'Priya': 'A',
'Rahul': 'B',
'Ravi': 'C'
}
# Accessing a value
Priya_grade = grades['Priya']
print(f"Priya's grade: {Priya_grade}")
# Using get() to access a value safely
Ravi_grade = grades.get('Ravi', 'Grade not available')
print(f"Ravi's grade: {Ravi_grade}")

You can also try this code with Online Python Compiler
Run Code
Outputs:
Priya's grade: A
Ravi's grade: C
Note : This method is efficient and simple, making it a fundamental aspect of working with dictionaries in Python.
Accessing an Element of a Nested Dictionary
Accessing elements within a nested dictionary in Python involves navigating through multiple levels of keys. It's like drilling down through layers to reach the specific data you need.
Let’s see how can we do it:
Python
# Example of a nested dictionary containing course details
university_courses = {
'Engineering': {
'Computer Science': {
'students': 300,
'faculty': 25
},
'Mechanical': {
'students': 200,
'faculty': 15
}
},
'Arts': {
'History': {
'students': 150,
'faculty': 12
},
'English': {
'students': 180,
'faculty': 18
}
}
}
# Accessing the number of students in the Computer Science course
cs_students = university_courses['Engineering']['Computer Science']['students']
print(f"Number of Computer Science students: {cs_students}")

You can also try this code with Online Python Compiler
Run Code
Output
Number of Computer Science students: 300
Note : This method allows you to retrieve detailed information efficiently, even from complex data structures.
Deleting Elements using the ‘del’ Keyword
Removing elements from a dictionary in Python can be achieved using the del keyword. This allows you to delete items by their key, effectively managing the contents of your dictionary.
Here’s how to use it:
Python
# Example dictionary
tech_tools = {
'IDE': 'PyCharm',
'Version Control': 'Git',
'Language': 'Python'
}
# Deleting an element by key
del tech_tools['Version Control']
print(tech_tools) # Outputs: {'IDE': 'PyCharm', 'Language': 'Python'}
# Attempting to delete a non-existent key results in KeyError
# del tech_tools['Compiler'] # Uncommenting this line would raise KeyError

You can also try this code with Online Python Compiler
Run Code
Output
{'IDE': 'PyCharm', 'Language': 'Python'}
Note : Using del is very easy, but care must be taken to ensure that the key exists to avoid errors. This method is part of effective dictionary management, especially when you need to dynamically adjust the contents of your data structures.
Dictionary Methods
Python dictionaries come equipped with several built-in methods that enhance their functionality and ease of use.
Here are some of the key methods you should know:
clear()
Removes all items from the dictionary, leaving it empty.
Python
my_dict = {'name': 'Priya', 'age': 25}
my_dict.clear()
print(my_dict)

You can also try this code with Online Python Compiler
Run Code
Outputs:
{}
copy()
Returns a shallow copy of the dictionary.
Python
original = {'name': 'Priya', 'age': 25}
copy_dict = original.copy()
print(copy_dict)

You can also try this code with Online Python Compiler
Run Code
Outputs:
{'name': 'Priya', 'age': 25}
keys()
Returns a view of the dictionary's keys.
Python
student = {'name': 'Gaurav', 'age': 22}
keys = student.keys()
print(list(keys))

You can also try this code with Online Python Compiler
Run Code
Outputs:
['name', 'age']
values()
Returns a view of the dictionary's values.
Python
student = {'name': 'Gaurav', 'age': 22}
values = student.values()
print(list(values))

You can also try this code with Online Python Compiler
Run Code
Outputs:
['Gaurav', 22]
items()
Returns a view of the dictionary's key-value pairs (tuples).
Python
student = {'name': 'Gaurav', 'age': 22}
items = student.items()
print(list(items))

You can also try this code with Online Python Compiler
Run Code
Outputs:
[('name', 'Gaurav'), ('age', 22)]
get()
Retrieves the value for a given key, allowing a default value if the key is not found.
Python
student = {'name': 'Gaurav', 'age': 22}
print(student.get('name', 'Not Found'))
print(student.get('major', 'Not Specified'))

You can also try this code with Online Python Compiler
Run Code
Outputs:
Gaurav
Not Specified
update()
Updates the dictionary with the key/value pairs from another dictionary or an iterable of key/value pairs.
Python
student_info = {'name': 'Gaurav', 'age': 22}
additional_info = {'grade': 'A', 'courses': ['Math', 'Science']}
student_info.update(additional_info)
print(student_info)

You can also try this code with Online Python Compiler
Run Code
Outputs:
{'name': 'Gaurav', 'age': 22, 'grade': 'A', 'courses': ['Math', 'Science']}
Multiple Dictionary Operations in Python
Working with multiple dictionaries together can enhance the flexibility and efficiency of your programs.
Here are some common operations that involve multiple dictionaries:
Merging Dictionaries
You can merge two or more dictionaries into one using the update() method or the ** operator. This is useful when you need to combine data from different sources.
Python
# Using update()
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)
# Using ** operator for merging dictionaries
merged_dict = {**dict1, **dict2}
print(merged_dict)

You can also try this code with Online Python Compiler
Run Code
Outputs:
{'a': 1, 'b': 3, 'c': 4}
{'a': 1, 'b': 3, 'c': 4}
Comparing Dictionaries
You can compare dictionaries to find keys or values that are common or unique between them. This is often used in data analysis and debugging.
Python
# Finding common keys
common_keys = dict1.keys() & dict2.keys()
print(common_keys)
# Finding keys unique to dict1
unique_keys = dict1.keys() - dict2.keys()
print(unique_keys)

You can also try this code with Online Python Compiler
Run Code
Outputs:
{'b'}
{'a'}
Dictionary Comprehensions
Just like list comprehensions, dictionary comprehensions allow you to create new dictionaries from existing ones in a concise manner.
Python
# Creating a new dictionary with only selected keys
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
selected_dict = {k: v for k, v in dict1.items() if v > 2}
print(selected_dict)

You can also try this code with Online Python Compiler
Run Code
Outputs
{'c': 3, 'd': 4}
Frequently Asked Questions
Can a Python dictionary have multiple keys with the same name?
No, each key in a Python dictionary must be unique. If you assign a value to an existing key, it will overwrite the previous value.
Is it possible to store different data types as values in a dictionary?
Yes, Python dictionaries can hold values of any data type, including numbers, strings, lists, tuples, and even other dictionaries.
How can I remove all items from a dictionary?
Use the clear() method on the dictionary to remove all items. This method empties the dictionary but keeps the dictionary object intact.
Conclusion
In this article, we discussed the fundamentals of Python dictionaries, a powerful data structure that allows you to store and retrieve data using key-value pairs. We learned how to create dictionaries using various methods, access and modify elements, work with nested dictionaries, and add or remove key-value pairs. Python dictionaries provide a convenient and efficient way to organize and manipulate data based on unique keys, making them valuable tools in a wide range of applications.
Recommendation Reading: