What is a Dictionary in Python?
A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, & you can use the key to access the value associated with it, much like you would look up a word in a dictionary to find its definition. This makes dictionaries highly efficient for retrieving data.
Keys in a dictionary are unique. This means you cannot have two entries with the same key, but you can have multiple keys with the same value. Values can be any type of data: numbers, strings, lists, or even another dictionary.
Here are some key characteristics of Python dictionaries:
-
Unordered: Dictionaries are unordered, meaning the items do not have a defined order. You cannot refer to an item by using an index.
-
Changeable: Dictionaries are mutable, which means you can change, add, or remove items after the dictionary has been created.
-
Indexed: Dictionaries are indexed by keys. Keys are used to retrieve values from the dictionary.
-
No Duplicates: Dictionary keys must be unique. If you try to use the same key more than once, the previous value will be overwritten.
-
Versatile: Dictionary values can be of any data type (string, int, boolean, list, etc.) & can even be another dictionary, but keys must be of an immutable data type such as strings, numbers, or tuples.
Dictionaries are optimized for retrieving data. They are used when you have a set of unique keys that map to values. For example, a dictionary could be used to store the names & ages of students, with the names being the keys & the ages being the values.
student_ages = {'Rahul': 20, 'Sinki': 22, 'Harsh': 21}
In this example, the keys are the names of the students (Rahul, Sinki, Harsh) & the values are their corresponding ages (20, 22, 21).
How to Create a Dictionary
Creating a dictionary in Python is straightforward. You can start with an empty dictionary & add key-value pairs to it, or you can create a dictionary with initial values. Here's how you can do both:
Creating an Empty Dictionary:
empty_dict = {}
This code sets up empty_dict as an empty dictionary with no keys or values. It's like starting with an empty container that you can fill with items later.
Adding Key-Value Pairs:
Once you have your dictionary, you can add items to it by using a new key & assigning a value to it:
empty_dict['new_key'] = 'value'
Here, 'new_key' is the key & 'value' is the value associated with that key. You can continue adding as many key-value pairs as you need.
Creating a Dictionary with Initial Values:
If you already know what data your dictionary should contain, you can create it with items in place:
filled_dict = {
'name': 'Rahul',
'age': 25,
'email': 'Rahul@example.com'
}
In filled_dict, we have three key-value pairs. The keys are 'name', 'age', and 'email', and the values are 'Rahul', 25, and 'Rahul@example.com' respectively.
Both methods are valid & the choice between them depends on your specific needs. If you know all the items you need to store from the beginning, initializing them directly is efficient. If your dictionary's content depends on conditions or has to be built over time, starting with an empty dictionary & adding to it could be more suitable.
Different Ways to Create a Python Dictionary
Python offers multiple methods to create dictionaries, catering to various scenarios & preferences. Each method has its advantages, depending on the structure of the data & the specific needs of your program. Let's explore some of these methods.
1. Using Curly Braces
The most direct way to create a dictionary is by using curly braces {} with key-value pairs as demonstrated earlier. This method is straightforward and widely used.
student = {
'name': 'Alice',
'grade': 'A',
'age': 22
}
2. Using the dict() Constructor
You can also create a dictionary using the dict() constructor. This method is useful when you have dynamic data or when you prefer a cleaner syntax without quotes for keys.
student = dict(name='Alice', grade='A', age=22)
Here, name, grade, and age are not passed as strings but as keyword arguments, making the code cleaner and often easier to read.
3. From a List of Tuples
If your data comes in pairs (like from a database or an external file), you can convert it into a dictionary using the dict() constructor with a list of tuples.
data = [('name', 'Alice'), ('grade', 'A'), ('age', 22)]
student = dict(data)
Each tuple contains two elements: the key and the value.
4. Using zip() with Two Lists
If you have two separate lists, one with keys and another with values, you can merge them into a dictionary using the zip() function combined with the dict() constructor.
keys = ['name', 'grade', 'age']
values = ['Alice', 'A', 22]
student = dict(zip(keys, values))
5. Using Dictionary Comprehensions
For more complex datasets or conditions, dictionary comprehensions offer a powerful way to create dictionaries. They work similarly to list comprehensions but produce key-value pairs instead of list items.
keys = ['name', 'grade', 'age']
values = ['Alice', 'A', 22]
student = {key: value for key, value in zip(keys, values)}
This method not only merges lists into a dictionary but also allows for conditionally including items.
Nested Dictionaries
Nested dictionaries are a powerful feature in Python that allows you to store a dictionary within another dictionary. This is particularly useful when you need to manage more complex data structures, like when each key in a dictionary corresponds to multiple attributes that are best represented as a dictionary themselves.
Understanding Nested Dictionaries
Imagine you're organizing information about a library. Each book might have details like its title, author, and genre, but you also want to include information about the borrower. A nested dictionary can handle this elegantly:
library = {
'Book1': {
'title': '1984',
'author': 'George Orwell',
'genre': 'Dystopian Fiction',
'borrower': {
'name': 'Pallavi Singh',
'return_date': '2024-01-01'
}
},
'Book2': {
'title': 'The Great Gatsby',
'author': 'F. Scott Fitzgerald',
'genre': 'Historical Fiction',
'borrower': {
'name': 'Lekhika',
'return_date': '2024-02-15'
}
}
}
In this example:
Each key like 'Book1' and 'Book2' points to another dictionary that holds details about a book.
The 'borrower' key itself points to another dictionary containing the borrower's name and the book's return date.
Accessing Elements in a Nested Dictionary
To retrieve information from a nested dictionary, you simply chain the keys together. For example, to get the return date for 'Book1':
return_date_book1 = library['Book1']['borrower']['return_date']
print("Return Date for Book1:", return_date_book1)
This will output:
Return Date for Book1: 2024-01-01
Adding and Modifying Data
Adding or modifying data in a nested dictionary follows the same principle. To add another book or update an existing entry, you use the keys to navigate through the levels of the dictionary:
# Adding a new book
library['Book3'] = {
'title': 'To Kill a Mockingbird',
'author': 'Harper Lee',
'genre': 'Thriller',
'borrower': None # Initially, no borrower
}
# Updating a borrower
library['Book1']['borrower']['name'] = 'Alice Johnson'
Nested dictionaries provide a structured way to handle multi-layered data, making it easier to organize complex information in a manageable and accessible format.
Adding Elements to a Dictionary
Adding elements to a Python dictionary is a straightforward process, allowing you to dynamically update the content of your dictionary as your application's requirements evolve. This functionality is key for adapting your data structures to changing conditions in your code.
Basic Method for Adding Elements
To add a new key-value pair to an existing dictionary, you simply assign a value to a new key. If the key already exists, its value will be updated; if it does not exist, the key-value pair will be added.
# Assume this is our initial dictionary
vehicle_info = {
'make': 'Toyota',
'model': 'Corolla',
'year': 2019
}
# Adding a new key-value pair
vehicle_info['color'] = 'red'
Now, vehicle_info includes a new key 'color' with the value 'red'. If you print vehicle_info, you'll see that it has been updated accordingly:
print(vehicle_info)
# Output: {'make': 'Toyota', 'model': 'Corolla', 'year': 2019, 'color': 'red'}
Using the update() Method
Another way to add elements is by using the update() method. This method is especially useful when you want to add multiple key-value pairs at once or merge another dictionary into the current one.
# Additional info to add
additional_info = {
'insurance_provider': 'Geico',
'insurance_policy_number': '1234567890'
}
# Using update to add the additional_info dictionary
vehicle_info.update(additional_info)
After calling update(), vehicle_info now contains entries for both the insurance provider and the policy number, demonstrating the efficiency of adding multiple elements simultaneously.
Considerations When Adding Elements
Keys in dictionaries are unique. Adding an element with a key that already exists will overwrite the existing value associated with that key.
There are no restrictions on the types of objects that can serve as values. You can store integers, strings, lists, or even other dictionaries.
Accessing Elements of a Dictionary
Accessing elements in a Python dictionary is a common task, enabling you to retrieve values associated with specific keys. This capability is fundamental for effectively using dictionaries to manage and manipulate data.
Using Keys to Access Values
To access a value in a dictionary, you use the key associated with the value you want to retrieve. Here's how you do it:
Python
# Assuming we have the following dictionary
person = {
'name': 'Emma',
'age': 30,
'city': 'New York'
}
# Accessing the name
person_name = person['name']
print("Name:", person_name) # Output: Name: Emma
# Accessing the age
person_age = person['age']
print("Age:", person_age)

You can also try this code with Online Python Compiler
Run Code
Output:
Name: Emma
Age: 30
In the example above, by specifying the key ('name' and 'age'), we directly fetch the values ('Emma' and 30) from the dictionary.
Handling Missing Keys with get()
Using direct key access can lead to errors if the key does not exist. To handle such cases more gracefully, you can use the get() method, which allows you to specify a default value if the key is missing.
# Accessing a key that might not exist
person_email = person.get('email', 'No email provided')
print("Email:", person_email)
Output:
Email: No email provided
Here, since 'email' is not a key in the person dictionary, get() returns the string 'No email provided'.
Benefits of Using get()
-
Safety: Prevents the program from crashing due to missing keys.
- Flexibility: Allows you to provide a default response when data is absent, which can be particularly useful in user-facing applications where providing feedback is crucial.
Access a Value in Python Dictionary
When working with Python dictionaries, accessing a value directly can be very straightforward. This process involves using the key of the value you want to retrieve, which acts like an address that points directly to the value stored in the dictionary.
Direct Access by Key
To demonstrate, consider a dictionary that stores user data:
Python
user = {
'username': 'coder123',
'email': 'coder123@example.com',
'membership_status': 'active'
}
# Accessing the email of the user
user_email = user['email']
print("User Email:", user_email)

You can also try this code with Online Python Compiler
Run Code
Output:
User Email: coder123@example.com
In this example, 'email' is the key used to access the user's email address. By providing the correct key, you can efficiently retrieve the corresponding value.
What Happens if the Key Doesn't Exist?
Attempting to access a value using a key that isn't in the dictionary will result in a KeyError. This error stops the execution of the program, which might not be desirable. To handle such situations, you can use methods that check for the key before access or provide a fallback:
Using get() to Safely Access Values
The get() method is a safer approach to access values, as it allows you to specify a default value if the key is not found:
Python
# Safely accessing a key with get()
membership_type = user.get('membership_type', 'None')
print("Membership Type:", membership_type)

You can also try this code with Online Python Compiler
Run Code
Output:
Membership Type: None
Here, since 'membership_type' is not a key in the user dictionary, get() returns 'None', avoiding a KeyError.
Benefits of Using get()
-
Safety: It prevents the program from crashing by handling missing keys gracefully.
- Control: It provides control over what is returned when the key is missing, allowing the flow of the program to continue seamlessly.
Accessing an Element of a Nested Dictionary
Nested dictionaries in Python are dictionaries that contain other dictionaries as values. Accessing elements in these nested structures can seem daunting at first, but it's quite logical once you understand the basic principles.
How to Access Elements in a Nested Dictionary:
Let's consider a nested dictionary that represents information about a company's employees, where each employee is identified by an ID and has personal details and job information as nested dictionaries:
company = {
'employee1': {
'name':’Gunjan Batra’,
'department': 'Finance',
'email': 'gbatra@example.com'
},
'employee2': {
'name': 'Mehak Goel',
'department': 'IT',
'email': 'mg@example.com'
}
}
To access elements within this nested dictionary, you chain the keys from the outer dictionary to the inner dictionary:
Accessing the Name of Employee1:
employee1_name = company['employee1']['name']
print("Employee 1 Name:", employee1_name)
Output:
Employee 1 Name: Gunjan Batra
Here, company['employee1'] accesses the dictionary associated with 'employee1', and appending ['name'] accesses the name value within that dictionary.
Handling Missing Keys in Nested Dictionaries
When dealing with nested dictionaries, the chance of encountering missing keys increases. To handle these cases without causing a KeyError, you can use nested get() methods to safely navigate through the layers:
Python
# Accessing a potentially missing key safely
employee3_department = company.get('employee3', {}).get('department', 'No Department')
print("Employee 3 Department:", employee3_department)

You can also try this code with Online Python Compiler
Run Code
Output:
Employee 3 Department: No Department
In this example, if 'employee3' does not exist, get() returns an empty dictionary {}, and the subsequent get('department', 'No Department') then returns 'No Department'. This prevents errors and allows the program to continue running smoothly.
Benefits of Accessing Nested Dictionaries Safely
-
Error Prevention: Avoids KeyError that can crash your program.
- Flexibility: Allows for the safe retrieval of data even in complex nested structures where some data may be optional or missing.
Deleting Elements Using the ‘del’ Keyword
In Python, the del keyword is used to remove elements from a dictionary. This can be particularly useful when you need to clean up or modify data within your program. Using del is straightforward and effectively frees up resources or prevents outdated data from causing errors.
How to Use the del Keyword
Consider a dictionary that stores user information, and you decide to remove an entry that is no longer necessary or relevant:
user_profile = {
'username': 'techguru',
'email': 'techguru@example.com',
'membership_status': 'active'
}
# Suppose we need to delete the email address
del user_profile['email']
After executing the del command, user_profile will no longer include the 'email' key and its associated value. Attempting to access it will result in a KeyError because it no longer exists in the dictionary:
# Trying to access the deleted key
try:
print(user_profile['email'])
except KeyError:
print("Email address not found.")
This will output "Email address not found."
Considerations When Using del
Key Existence: Before using del, it's good practice to ensure that the key exists to avoid KeyError. You can do this by checking if the key is in the dictionary:
if 'email' in user_profile:
del user_profile['email']
else:
print("Key not found.")
Impact on Program: Removing elements can affect iterations, calculations, or conditions dependent on the dictionary. Ensure that deleting an element doesn't break other parts of your program.
Alternatives to del
The pop() method is another way to remove items from a dictionary. It also lets you retrieve the value while removing the key:
# Using pop to remove and get the value
membership_status = user_profile.pop('membership_status', 'No status')
print("Removed membership status:", membership_status)
This command removes the 'membership_status' key and prints the removed value. If the key doesn’t exist, it returns 'No status' instead of raising an error.
Dictionary Methods
Python dictionaries come equipped with several built-in methods that facilitate effective management and manipulation of their data. These methods are essential for performing various routine operations such as adding, removing, or modifying elements within dictionaries. Here are some of commonly used dictionary methods with an example of how to use them :
1. clear() - Remove All Items
The clear() method empties the dictionary, leaving it with zero elements.
Python
info = {'name': 'Alice', 'age': 25, 'city': 'New York'}
info.clear()
print(info)

You can also try this code with Online Python Compiler
Run Code
Output:
{}
2. copy() - Returns a Shallow Copy
The copy() method creates a copy of the dictionary. Changes to the copy do not affect the original dictionary.
Python
original = {'name': 'Bob', 'age': 30}
copy_dict = original.copy()
copy_dict['age'] = 31 # Changing the copy does not affect the original
print(original)

You can also try this code with Online Python Compiler
Run Code
Output:
{'name': 'Bob', 'age': 30}
3. get(key[, default]) - Return the value for key if key is in the dictionary, else default
This method is safer than direct key access because it returns a default value if the key is not found.
Python
employee = {'name': 'Jane', 'department': 'Marketing'}
print(employee.get('age', 'No Age Provided'))

You can also try this code with Online Python Compiler
Run Code
Output:
No Age Provided
4. items() - Return a new view of the dictionary’s items (key, value pairs)
This is useful for looping over the dictionary to access keys and values.
for key, value in employee.items():
print(f"{key}: {value}")
5. keys() - Return a new view of the dictionary’s keys
This method allows you to iterate over keys or check if certain keys exist.
if 'name' in employee.keys():
print("Name is available.")
6. values() - Return a new view of the dictionary’s values
Useful for various operations that involve only values.
values = employee.values()
print(values)
Output:
dict_values(['Jane', 'Marketing'])
7. pop(key[, default]) - Remove the specified key and return the corresponding value
If the key is not found, default is returned if provided, else KeyError is raised.
print(employee.pop('age', 'No Age Found'))
Output:
No Age Found
8. popitem() - Remove and return a (key, value) pair as a 2-tuple
Pairs are returned in LIFO order. Useful in scenarios where items need to be processed and removed one by one.
print(employee.popitem())
Output:
('department', 'Marketing')
9. update([other]) - Update the dictionary with the key/value pairs from other, overwriting existing keys
This method is used to merge two dictionaries.
Python
employee.update({'age': 30, 'city': 'New York'})
print(employee)

You can also try this code with Online Python Compiler
Run Code
Output:
{'name': 'Jane', 'department': 'Marketing', 'age': 30, 'city': 'New York'}
Multiple Dictionary Operations in Python
Working with multiple dictionaries in Python involves techniques that help you combine, compare, and manipulate several dictionaries simultaneously. This can be useful in scenarios where data is distributed across various dictionaries and needs to be processed in a unified manner. Here’s how you can perform multiple dictionary operations efficiently.
1. Merging Dictionaries
Python provides several ways to merge dictionaries. One common approach is using the update() method, which modifies a dictionary in-place by adding key-value pairs from another dictionary. Another modern and efficient way introduced in Python 3.9 is using the merge operator (|).
Example of merging using update():
Python
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)

You can also try this code with Online Python Compiler
Run Code
Output:
{'a': 1, 'b': 3, 'c': 4}
Example of merging using the merge operator:
Python
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
combined_dict = dict1 | dict2
print(combined_dict)

You can also try this code with Online Python Compiler
Run Code
Output:
{'a': 1, 'b': 3, 'c': 4}
In both cases, if there are overlapping keys, the value from the second dictionary (dict2) will overwrite the value from the first (dict1).
2. Finding Common Keys
To find keys that are common to two or more dictionaries, you can use set operations on the keys.
Example of finding common keys:
Python
keys_dict1 = set(dict1.keys())
keys_dict2 = set(dict2.keys())
common_keys = keys_dict1 & keys_dict2
print(common_keys)

You can also try this code with Online Python Compiler
Run Code
Output:
{'b'}
3. Dictionary Comprehensions
You can use dictionary comprehensions to create new dictionaries based on existing ones, allowing for the inclusion of conditional logic.
Example of filtering a dictionary:
Python
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in dict1.items() if v > 2}
print(filtered_dict)

You can also try this code with Online Python Compiler
Run Code
Output:
{'c': 3, 'd': 4}
Here, filtered_dict contains only the items from dict1 where the values are greater than 2.
4. Combining Multiple Operations
In practice, you may often need to combine these operations. For example, merging two dictionaries and then filtering the result based on a certain condition.
Python
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = dict1 | dict2
result_dict = {k: v for k, v in merged_dict.items() if v % 2 == 0}
print(result_dict)

You can also try this code with Online Python Compiler
Run Code
Output:
{'b': 2, 'd': 4}
This example merges dict1 and dict2, and then creates a new dictionary that includes only the even values.
Frequently Asked Questions
Can I use non-string types as dictionary keys in Python?
Yes, you can use any immutable type as a dictionary key in Python. This includes integers, floats, tuples, and more. However, types like lists or dictionaries cannot be used because they are mutable.
How can I prevent errors when accessing a non-existent key in a dictionary?
To avoid errors when a key does not exist, use the get() method, which allows you to specify a default value if the key is absent, preventing a KeyError.
Is it possible to sort a dictionary by its values?
Yes, you can sort a dictionary by its values using the sorted() function along with a key argument, like so: sorted(my_dict.items(), key=lambda item: item[1]). This returns a list of tuples sorted by the values.
Conclusion
In this article, we've talked about creating and using dictionaries in Python, learned their syntax, methods, and various operations for managing and manipulating data efficiently. From understanding basic dictionary structures and accessing elements safely to performing advanced operations involving multiple dictionaries, we talked about everything with proper examples.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.