Mastering Python Dictionaries: A Comprehensive Guide!

Discover the full potential of Python’s built-in dictionary type with this in-depth article.

Aarafat Islam
6 min readJan 6, 2023

“The beauty of a dictionary is that it is both a data structure and a hash table, so you get both fast access and fast searching. It’s the best of both worlds.” — Wesley Chun

Photo by Shubham Dhage on Unsplash

A dictionary in Python is a collection of unordered, changeable, and indexed data elements. It is similar to a list or an array in other programming languages, but with a few key differences. In a list, data elements are ordered and can be accessed by their index number. In a dictionary, data elements are stored as key-value pairs, and the key is used to access the corresponding value.

Creating a Python Dictionary

To create a dictionary in Python, you can use the dict function or enclose a comma-separated list of key-value pairs in curly braces {}. For example:

# Using the dict function
empty_dict = dict()

# Using curly braces
colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

You can also create a dictionary using the zip function and two lists of equal length, where the first list contains the keys and the second list contains the values. Here's an example:

# Using the zip function
keys = ["red", "green", "blue"]
values = ["#FF0000", "#00FF00", "#0000FF"]

colors = dict(zip(keys, values))

Accessing Elements in a Python Dictionary

To access an element in a dictionary, you can use the square brackets [] and the key of the element you want to access. For example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

red_color = colors["red"]
print(red_color) # Output: "#FF0000"

If the key you are trying to access does not exist in the dictionary, you will get an KeyError exception. To avoid this, you can use the get method, which returns a default value if the key is not found. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

orange_color = colors.get("orange", "Key not found")
print(orange_color) # Output: "Key not found"

Modifying Elements in a Python Dictionary

To modify an element in a dictionary, you can use the assignment operator = and the key of the element you want to modify. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

colors["red"] = "#F00"
print(colors) # Output: {'red': '#F00', 'green': '#00FF00', 'blue': '#0000FF'}

You can also add a new element to a dictionary by assigning a value to a key that does not exist in the dictionary. Here’s an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

colors["orange"] = "#FF7F00"
print(colors) # Output: {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF', 'orange': '#FF7F00'}

To remove an element from a dictionary, you can use the pop method and the key of the element you want to remove. The pop method removes the element from the dictionary and returns its value. If the key is not found, it returns a default value. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

red_color = colors.pop("red", "Key not found")
print(colors) # Output: {'green': '#00FF00', 'blue': '#0000FF'}
print(red_color) # Output: "#FF0000"

You can also use the del statement to remove an element from a dictionary. The del statement does not return the value of the removed element. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

del colors["red"]
print(colors) # Output: {'green': '#00FF00', 'blue': '#0000FF'}

To remove all elements from a dictionary, you can use the clear method. This method removes all elements from the dictionary, but the dictionary itself is not deleted. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

colors.clear()
print(colors) # Output: {}

Iterating Over a Python Dictionary

To iterate over a dictionary in Python, you can use a for loop and the items method, which returns a list of key-value pairs. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

for key, value in colors.items():
print(key, value)

# Output:
# red #FF0000
# green #00FF00
# blue #0000FF

You can also use the keys and values methods to iterate over the keys and values separately. Here are some examples:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

# Iterating over the keys
for key in colors.keys():
print(key)

# Output:
# red
# green
# blue

# Iterating over the values
for value in colors.values():
print(value)

# Output:
# #FF0000
# #00FF00
# #0000FF

Python Dictionary Built-in Functions and Methods

Python dictionaries have a number of built-in functions and methods that you can use to perform various operations. Here are some examples:

  • len(dictionary): Returns the length of the dictionary (i.e., the number of key-value pairs).
  • str(dictionary): Returns a string representation of the dictionary.
  • dict(zip(keys, values)): Creates a new dictionary from two lists of equal length, where the first list contains the keys and the second list contains the values.
  • dictionary.clear(): Removes all elements from the dictionary.
  • dictionary.copy(): Returns a shallow copy of the dictionary.
  • dictionary.fromkeys(keys[, value]): Creates a new dictionary with the specified keys and a default value.
  • dictionary.get(key[, default]): Returns the value of the specified key, or a default value if the key is not found.
  • dictionary.items(): Returns a view object that displays a list of the dictionary's key-value pairs.
  • dictionary.keys(): Returns a view object that displays a list of the dictionary's keys.
  • dictionary.pop(key[, default]): Removes the specified key and returns its value, or a default value if the key is not found.
  • dictionary.popitem(): Removes an arbitrary key-value pair from the dictionary and returns it as a tuple.
  • dictionary.setdefault(key[, default]): Returns the value of the specified key, or sets a default value if the key is not found.
  • dictionary.update(other_dictionary): Updates the dictionary with the key-value pairs from another dictionary.
  • dictionary.values(): Returns a view object that displays a list of the dictionary's values.

Python Dictionary Comprehensions

You can use dictionary comprehensions to create a new dictionary from an iterable in a single line of code. A dictionary comprehension consists of an expression followed by a for clause, followed by a if clause (optional). Here's an example:

# Dictionary comprehension
numbers = {x: x**2 for x in range(10)}
print(numbers) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

You can also use the if clause to filter the elements of the iterable. Here's an example:

# Dictionary comprehension with filter
even_numbers = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_numbers) # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Python Dictionary Membership Test

You can use the in and not in operators to test if a key or value exists in a dictionary. Here's an example:

colors = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

# Membership test for keys
print("red" in colors) # Output: True
print("orange" in colors) # Output: False

# Membership test for values
print("#FF0000" in colors.values()) # Output: True
print("#FF7F00" in colors.values()) # Output: False

Python Dictionary Comparison

You can use the == and != operators to compare dictionaries. Two dictionaries are considered equal if they have the same key-value pairs. Here's an example:

colors1 = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

colors2 = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF"
}

colors3 = {
"red": "#F00",
"green": "#0F0",
"blue": "#00F"
}

# Comparison
print(colors1 == colors2) # Output: True
print(colors1 == colors3) # Output: False
print(colors1 != colors2) # Output: False
print(colors1 != colors3) # Output: True

Python Dictionary Example

Here is an example of how you can use dictionaries in Python to store and manipulate data:

# Dictionary example

# Initialize variables
employee_1 = {
"name": "John Smith",
"age": 30,
"department": "Sales"
}

employee_2 = {
"name": "Jane Doe",
"age": 25,
"department": "Marketing"
}

employee_3 = {
"name": "Bob Johnson",
"age": 35,
"department": "IT"
}

employees = [employee_1, employee_2, employee_3]

# Find employees over 30
over_30 = [e for e in employees if e["age"] > 30]
print(over_30) # Output: [{'name': 'Bob Johnson', 'age': 35, 'department': 'IT'}]

# Increase ages by 5
for e in employees:
e["age"] += 5
print(employees) # Output: [{'name': 'John Smith', 'age': 35, 'department': 'Sales'}, {'name': 'Jane Doe', 'age': 30, 'department': 'Marketing'}, {'name': 'Bob Johnson', 'age': 40, 'department': 'IT'}]

# Change department of employee with name "Jane Doe"
for e in employees:
if e["name"] == "Jane Doe":
e["department"] = "HR"
print(employees) # Output: [{'name': 'John Smith', 'age': 35, 'department': 'Sales'}, {'name': 'Jane Doe', 'age': 30, 'department': 'HR'}, {'name': 'Bob Johnson', 'age': 40, 'department': 'IT'}]

In conclusion, dictionaries are a powerful and integral part of Python programming, providing a convenient way to store and manipulate data. With their ability to efficiently store key-value pairs, dictionaries can be used in a variety of applications, from storing employee records to organizing word counts in a document. Understanding and utilizing the various functions and methods of dictionaries can greatly enhance the capabilities of your Python programs.

--

--

Aarafat Islam

🌎 A Philomath | Predilection for AI, DL | Blockchain | Researcher | Technophile | True Optimist | Endeavors to make impact on the world! ✨