No, Python dictionaries cannot have duplicate keys. If a duplicate key is added, the last value for that key will overwrite the previous one.
my_dict = {'apple': 2, 'apple': 4}
print(my_dict) # Output: {'apple': 4}
Python dictionaries are one of the most widely used data structures in Python. They allow us to store and manage data in key-value pairs, offering quick lookups and flexibility when working with complex data.
A Python dictionary is defined by placing key-value pairs inside curly braces {}
, separated by commas. Each key is unique and corresponds to a specific value.
Ordered or unordered: Starting from Python 3.7, dictionaries maintain the insertion order of items. Before that, dictionaries were unordered collections. This means that in modern Python versions, the order in which you add items to a dictionary is preserved.
Changeable: Python dictionaries are mutable, allowing you to change, add, or remove items after their creation.
Duplicates not allowed: Keys must be unique in a dictionary. If you add a duplicate key, it will overwrite the existing key’s value. However, values can be duplicated.
Dictionaries are extremely useful when you need to store data that can be easily searched and accessed via unique keys. Some common use cases are:
Storing user data, such as profiles or settings.
Implementing fast lookups for data like configuration files.
Counting the frequency of elements in a dataset.
We have other data structures such as List
, Set
in Python. Therefore, it is important to know when to use dictionaries.
Python dictionaries are optimized versions of HashMap.
HashMaps are developed for faster lookups.
Use Python dictionaries when there is a need to search elements faster.
The time complexity to set, get, and delete an item in a dictionary is
.
Each item in a dictionary is a key-value pair. Keys must be immutable (such as strings, numbers, or tuples), while values can be of any data type.
In the following code, we create a dictionary with mixed data types for values.
# Define a dictionary with various data typesmy_dict = {"name": "John", # A string value representing the person's name"age": 25, # An integer value representing the person's age"is_student": True, # A boolean value indicating if the person is a student"courses": ["Math", "Science"] # A list of courses the person is enrolled in}# Print the entire dictionaryprint("Dictionary items:", my_dict) # Output the dictionary to see its contents
In this dictionary, the keys are strings ("name"
, "age"
, "is_student"
, "courses"
) and the values are of mixed types, such as strings, integers, booleans, and lists.
Try adding a course "Chemistry" in the above code and observe the change in the output.
There are multiple ways to create dictionaries in Python. Here are the most common methods.
{}
The simplest method to create a dictionary is using curly braces {}
.
# Create a dictionary using curly bracesmy_dict = {"name": "Alice", # A string value representing the person's name"age": 30, # An integer value representing the person's age"city": "New York" # A string value representing the person's city}# Print the created dictionaryprint("Created dictionary using curly braces:", my_dict) # Output the dictionary to see its contents
dict()
functionWe can also create a dictionary in Python with the dict()
function:
# Create a dictionary using the dict() constructormy_dict = dict(name="Bob", age=40, city="London") # Create a dictionary with keys and values as parameters# Print the created dictionaryprint("Created dictionary using dict():", my_dict) # Output the dictionary to see its contents
We can create an empty dictionary and later on add items in it as according to requirements:
# Create an empty dictionaryempty_dict = {} # Initialize an empty dictionary# Print the empty dictionaryprint("Empty dictionary:", empty_dict) # Output the empty dictionary to confirm it's created
Each method creates a dictionary where keys are associated with specific values. You can use either curly braces {}
or the dict()
function.
Dictionary values can be accessed by using the key inside square brackets or the get()
method:
# Accessing dictionary values using keymy_dict = {"name": "Alice", "age": 30}# Access value using square bracketsprint("Name using square brackets:", my_dict["name"])# Access value using get() methodprint("Age using get():", my_dict.get("age"))# Example of get() returning None if the key does not existprint("City using get() (non-existing key):", my_dict.get("city"))
We can access values in a dictionary using either square brackets []
or the get()
method. The get()
method returns None
if the key is not found, while using square brackets raises a KeyError
.
Try modifying the code to handle the case where the key ("city") doesn't exist by using the get()
method with a default value.
To add a new key-value pair to a dictionary, simply assign a value to a new key.
# Adding items to the dictionarymy_dict = {"name": "Steve", "age": 30}my_dict["city"] = "Seattle"# Output the updated dictionaryprint("Updated dictionary after adding city:", my_dict)
We add a new key "city"
and assign the value "Paris"
to it. The dictionary is updated in-place.
You can remove items from a dictionary using several methods, including pop()
, del
, and clear()
.
# Removing an item using pop()my_dict = {"name": "Alice", "age": 30, "city": "Paris"}removed_item = my_dict.pop("age")# Output the removed item and updated dictionaryprint("Removed item:", removed_item)print("Updated dictionary after removing 'age':", my_dict)# Removing an item using deldel my_dict["city"]print("Updated dictionary after removing 'city':", my_dict)# Removing all dictionary items with clear()my_dict_new = {"name": "Alice", "age": 30, "city": "Paris"}print("New dictionary before clear: ", my_dict_new)my_dict_new.clear()print("New dictionary after clear: ", my_dict_new)
In the above code, items are removed from the dictionary using:
pop()
: Returned the removed value.
del
: Removed the key-value pair without returning anything.
clear()
: Removed all elements from the dictionary.
You can change the value of an existing key by assigning a new value to that key.
# Changing a value in the dictionarymy_dict = {"name": "Alice", "age": 30}my_dict["age"] = 35# Output the updated dictionaryprint("Updated dictionary after changing 'age':", my_dict)
We modify the value of the key "age"
from 30
to 35
in the dictionary.
You can iterate over a dictionary’s keys, values, or both using loops.
my_dict = {"name": "Alice", "age": 30, "city": "Paris"}# Iterate over keysfor key in my_dict:print("Key:", key)# Iterate over valuesfor value in my_dict.values():print("Value:", value)# Iterate over key-value pairsfor key, value in my_dict.items():print(f"{key}: {value}")
The items()
method allows to iterate over key-value pairs, while the keys()
and values()
methods iterate over just keys and values, respectively.
Here are some useful methods for working with dictionaries.
my_dict = {"name": "Alice", "age": 30}# items() methodprint("Dictionary items:", my_dict.items())# keys() methodprint("Dictionary keys:", my_dict.keys())# values() methodprint("Dictionary values:", my_dict.values())# clear() method to empty the dictionarymy_dict.clear()print("Dictionary after using clear():", my_dict)
Python provides several built-in methods to manipulate dictionaries, including methods to get keys, values, and key-value pairs. The clear()
method removes all items from the dictionary.
Before we wrap up, let’s put your knowledge of Python dictionaries to a quick challenge!
Count the frequency of elements in a list using a dictionary
Task: Write a function that takes a list as input and returns a dictionary where the keys are the elements of the list, and the values are the frequencies of those elements.
Input list
input_list
= ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'
]
Expected output
{‘apple’: 3, ‘banana’: 2, ‘orange’: 1
}
def count_frequencies(input_list):# Write your code herereturn None
If you are stuck after you try, you can refer to the given solution by pressing the "Run" button.
Key takeaways
Python dictionaries are a powerful and flexible way to store and retrieve data in key-value pairs, offering fast lookups.
Dictionaries are mutable, meaning you can add, remove, or modify key-value pairs after creation.
Starting from Python 3.7, dictionaries maintain insertion order, meaning that the order in which you add items is preserved.
Python dictionaries do not allow duplicate keys, but values can be duplicated.
You can access dictionary values using keys or by using methods like get()
, which returns None
if the key does not exist.
Dictionaries are ideal for storing data where quick lookups based on unique keys are required, such as user profiles, settings, or fast element lookups.
Become a Data Analyst with our comprehensive learning path!
Unlock the power of data with our Become a Data Analyst path. Whether you’re a beginner or looking to transition into a data-driven career, this step-by-step journey will equip you with the skills to turn raw data into actionable insights.
From mastering SQL, Python, to learning data visualization and showcasing your analytical skills, this path has it all. Develop expertise in data cleaning, analysis, and storytelling to make informed decisions and drive business success.With hands-on practice, portfolio-building projects, and personalized guidance from our AI mentor, you’ll gain the confidence and knowledge to excel in interviews and secure your first job as a Data Analyst.
Start your data journey today!
Haven’t found what you were looking for? Contact Us