Data Structures: Dictionaries

Dive into dictionaries, a powerful data structure for storing key-value pairs. Learn how to create, access, modify, and iterate through dictionaries.


Data Structures: Dictionaries in Python

Dictionaries are a fundamental and powerful data structure in Python. They allow you to store and retrieve data using key-value pairs. Think of them like real-world dictionaries: you look up a word (the key) to find its definition (the value).

What are Dictionaries?

Unlike lists and tuples which are indexed by numbers, dictionaries are indexed by keys. These keys must be immutable (e.g., strings, numbers, tuples) while the values can be any Python data type. Dictionaries are also mutable, meaning you can change their contents after they are created.

Creating Dictionaries

You can create a dictionary using curly braces {} or the dict() constructor. Let's look at some examples:

 # Empty dictionary
my_dict = {}
my_dict = dict()

# Dictionary with initial values
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Using dict() constructor with keyword arguments
person2 = dict(name="Bob", age=25, city="London")

print(my_dict)    # Output: {}
print(person)     # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person2)    # Output: {'name': 'Bob', 'age': 25, 'city': 'London'} 

Accessing Values

You can access values in a dictionary using the key enclosed in square brackets [] or using the get() method.

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

# Accessing using square brackets
name = person["name"]  # Returns "Alice"
print(f"Name: {name}")

# Accessing using get() method
age = person.get("age") # Returns 30
print(f"Age: {age}")

# get() returns None if the key is not found (or you can specify a default value)
country = person.get("country") # Returns None
print(f"Country: {country}")

country = person.get("country", "Unknown") # Returns "Unknown" if "country" is not in the dictionary
print(f"Country: {country}")

#Trying to access a non-existent key with square brackets will raise a KeyError:
#city = person["country"] # Raises a KeyError! 

Modifying Dictionaries

Dictionaries are mutable, so you can add, update, or delete key-value pairs.

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

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

# Updating an existing value
person["age"] = 31
print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}

# Deleting a key-value pair using del
del person["city"]
print(person) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer'}

#Deleting using pop() which also returns the deleted value
occupation = person.pop("occupation")
print(person) # Output: {'name': 'Alice', 'age': 31}
print(occupation) #Output: Engineer

#Deleting using popitem(), which removes and returns the last inserted (key, value) pair.

person["city"] = "Paris"
lastItem = person.popitem()
print(person) #Output: {'name': 'Alice', 'age': 31}
print(lastItem) #Output: ('city', 'Paris') 

Iterating Through Dictionaries

You can iterate through a dictionary in various ways:

  • Iterating through keys: You can loop through the keys of a dictionary using a for loop directly on the dictionary itself or using the .keys() method.
  • Iterating through values: You can loop through the values of a dictionary using the .values() method.
  • Iterating through key-value pairs: You can loop through the key-value pairs (items) of a dictionary using the .items() method.
 person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Iterating through keys
print("Iterating through keys:")
for key in person: # or for key in person.keys():
    print(key)

# Iterating through values
print("\nIterating through values:")
for value in person.values():
    print(value)

# Iterating through key-value pairs
print("\nIterating through key-value pairs:")
for key, value in person.items():
    print(f"{key}: {value}") 

Dictionary Methods

Python dictionaries have several built-in methods that can be useful:

  • len(dict): Returns the number of items (key-value pairs) in the dictionary.
  • dict.keys(): Returns a view object that displays a list of all the keys in the dictionary.
  • dict.values(): Returns a view object that displays a list of all the values in the dictionary.
  • dict.items(): Returns a view object that displays a list of a dictionary's key-value tuple pairs.
  • dict.get(key, default=None): Returns the value for the given key. If the key is not present, it returns default.
  • dict.update(other_dict): Updates the dictionary with the key-value pairs from other_dict, overwriting existing keys.
  • dict.pop(key, default): Removes the specified key and returns the corresponding value. If key is not found, and default is given, it returns default. If key is not found and default is not given, it raises a KeyError.
  • dict.popitem(): Removes and returns the last inserted (key, value) pair from the dictionary.
  • dict.clear(): Removes all items from the dictionary.
  • dict.copy(): Returns a shallow copy of the dictionary.
  • dict.setdefault(key, default=None): If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

Conclusion

Dictionaries are an essential part of Python programming. They provide a flexible and efficient way to store and retrieve data using key-value pairs. Understanding how to create, access, modify, and iterate through dictionaries is crucial for writing effective Python code. Mastering dictionaries unlocks a lot of powerful programming patterns.