Dictionaries in Python are a versatile and powerful data structure that allows you to store and retrieve data in a structured and efficient manner. They are similar to hash maps or associative arrays in other programming languages. Dictionaries are unordered collections of key-value pairs, where each key is unique. Here’s everything you need to know about dictionaries in Python:

Creating a dictionary

You can create a dictionary by enclosing a comma-separated list of key-value pairs within curly braces ({}). Each key-value pair consists of a key followed by a colon (:) and its associated value.

# Creating an empty dictionary
empty_dict = {}
# Creating a dictionary with initial data
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}

In this example, person is a dictionary with keys "name", "age", and "city", each associated with respective values.

Dictionary keys

Dictionary keys must be unique and immutable. Common key types include strings, numbers, and tuples (since tuples are immutable). Keys are used to access values in the dictionary and must be unique within the dictionary.

# Valid dictionary keys
valid_dict = {
"key1": "value1",
42: "value2",
(1, 2): "value3"
}

In this example, keys are a string, an integer, and a tuple.

Accessing values

You can access the values in a dictionary by using square brackets ([]) and specifying the key. If the key is not found, it raises a KeyError exception.

# Accessing values in a dictionary
name = person["name"] # Retrieves the value associated with the key "name"
age = person["age"]
print(name, age) # Output: Alice 30

Alternatively, you can use the .get() method to access values safely, providing a default value if the key does not exist:

city = person.get("city", "Unknown") # If "city" key does not exist, it returns "Unknown"
print(city) # Output: New York

Modifying and adding items

You can change the value associated with a key by assigning a new value to it, or you can add new key-value pairs to the dictionary.

# Modifying values in a dictionary
person["age"] = 31 # Update the age to 31

# Adding a new key-value pair
person["gender"] = "Female"
print(person)
# Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'gender': 'Female'}

Removing items

You can remove a key-value pair from a dictionary using the del statement or the .pop() method.

# Removing a key-value pair using del
del person["gender"]

# Removing a key-value pair using pop
city = person.pop("city")
print(person) # Output: {'name': 'Alice', 'age': 31}
print(city) # Output: New York

Dictionary methods

Dictionaries in Python have several built-in methods for performing various operations:

  • .keys(): Returns a list of all keys in the dictionary.

  • .values(): Returns a list of all values in the dictionary.

  • .items(): Returns a list of key-value pairs (tuples) in the dictionary.

  • .clear(): Removes all key-value pairs from the dictionary.

  • .copy(): Creates a shallow copy of the dictionary.

  • .update(): Updates the dictionary with key-value pairs from another dictionary or iterable.

keys = person.keys()
values = person.values()
items = person.items()
print(keys) # Output: dict_keys(['name', 'age'])
print(values) # Output: dict_values(['Alice', 31])
print(items) # Output: dict_items([('name', 'Alice'), ('age', 31)])

Dictionary comprehensions

Python supports dictionary comprehensions, allowing you to create dictionaries using a compact and expressive syntax.

numbers = {x: x**2 for x in range(1, 6)} # Creates a dictionary of squares
print(numbers) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Dictionary nesting

Dictionaries can be nested inside other dictionaries or combined with other data structures to create more complex data structures.

students = {
"Alice": {"age": 20, "major": "Math"},
"Bob": {"age": 22, "major": "Computer Science"}
}
print(students)
# Output: {'Alice': {'age': 20, 'major': 'Math'}, 'Bob': {'age': 22, 'major': 'Computer Science'}}

Use cases

Dictionaries are widely used in Python for various purposes, including:

  • Storing configuration settings.

  • Representing structured data (e.g., JSON data).

  • Counting occurrences of items.

  • Building lookup tables for quick access to values.

  • Storing data with meaningful labels or keys.

Example: Counting Occurence
words = ["apple", "banana", "apple", "cherry", "banana", "banana"]
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count) # Output: {'apple': 2, 'banana': 3, 'cherry': 1}

Quiz Question

True or False. A dictionary in Python can have multiple values for a single key.

Quiz Question

How do you access the value associated with the key “age” in the following dictionary?

person = {
"name": "Alice",
"age": 30,
"city": "New York"
}

Quiz Question

What will be the output of the following code?

data = {'a': 1, 'b': 2, 'c': 3}
key = 'd'
print(data.get(key, "Not Found"))

Overall…

Dictionaries are a fundamental and versatile data structure in Python, providing an efficient way to work with key-value data. They are essential for a wide range of applications in programming and data manipulation, making them an indispensable tool in any Python programmer's toolkit.