Python Dictionaries

In Python, a dictionary is an unordered collection of key-value pairs. Each key is unique, and it maps to a specific value. Dictionaries are useful when you need to associate a unique key with a value, such as in cases like storing user information or counting occurrences.

1. Creating a Dictionary

You can create a dictionary by using curly braces {} with key-value pairs separated by colons :. The key-value pairs are separated by commas.

Example:

# Creating a dictionary with string keys and values
person = {"name": "John", "age": 30, "city": "New York"}

# Creating a dictionary with mixed data types
person = {"name": "Alice", "age": 25, "is_student": True}

# Creating a dictionary with integer keys
student_scores = {101: 85, 102: 90, 103: 88}

2. Accessing Dictionary Elements

You can access the value associated with a specific key using square brackets []. If the key does not exist, it will raise a KeyError.

Example:

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

# Accessing values using keys
print(person["name"])  # Output: John
print(person["age"])   # Output: 30

Alternatively, you can use the get() method to access the value. The advantage of get() is that it will return None (or a default value) if the key is not found, instead of raising an error.

print(person.get("city"))  # Output: New York
print(person.get("address"))  # Output: None (since "address" doesn't exist)

3. Adding and Modifying Elements

You can add new key-value pairs or modify existing ones by using the key in square brackets.

Example:

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

# Adding a new key-value pair
person["email"] = "[email protected]"

# Modifying an existing value
person["age"] = 31

print(person)
# Output: {'name': 'John', 'age': 31, 'city': 'New York', 'email': '[email protected]'}

4. Removing Elements

There are several ways to remove elements from a dictionary:

  • del to remove a key-value pair.
  • pop() to remove a key-value pair and return the value.
  • popitem() to remove the last inserted key-value pair (useful for dictionaries ordered by insertion).
  • clear() to remove all elements from the dictionary.

Example:

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

# Using del to remove a key-value pair
del person["age"]
print(person)  # Output: {'name': 'John', 'city': 'New York'}

# Using pop() to remove a key-value pair and get the value
city = person.pop("city")
print(person)  # Output: {'name': 'John'}
print("Removed city:", city)  # Output: Removed city: New York

# Using popitem() to remove the last inserted key-value pair
person["email"] = "[email protected]"
person["address"] = "123 Street"
removed_item = person.popitem()
print(person)  # Output: {'name': 'John', 'email': '[email protected]'}
print("Removed item:", removed_item)  # Output: Removed item: ('address', '123 Street')

# Using clear() to remove all key-value pairs
person.clear()
print(person)  # Output: {}

5. Accessing Dictionary Keys, Values, and Items

You can access the keys, values, and key-value pairs using the following methods:

  • keys() returns a view of the dictionary’s keys.
  • values() returns a view of the dictionary’s values.
  • items() returns a view of the dictionary’s key-value pairs.

Example:

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

# Accessing keys
print(person.keys())  # Output: dict_keys(['name', 'age', 'city'])

# Accessing values
print(person.values())  # Output: dict_values(['John', 30, 'New York'])

# Accessing key-value pairs
print(person.items())  # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

# Iterating over keys and values
for key, value in person.items():
    print(key, ":", value)
# Output:
# name : John
# age : 30
# city : New York

6. Dictionary Length

You can find the number of key-value pairs in a dictionary using the len() function.

Example:

person = {"name": "John", "age": 30, "city": "New York"}
print(len(person))  # Output: 3

7. Nested Dictionaries

A dictionary can contain other dictionaries as values, creating a nested dictionary. You can access nested values by chaining keys.

Example:

person = {
    "name": "John",
    "address": {"street": "123 Main St", "city": "New York", "zip": "10001"},
    "age": 30
}

# Accessing a nested value
print(person["address"]["city"])  # Output: New York

8. Merging Dictionaries

You can merge dictionaries in Python using the update() method or the | operator (Python 3.9+).

Example (using update()):

person = {"name": "John", "age": 30}
address = {"city": "New York", "zip": "10001"}

# Merging two dictionaries
person.update(address)
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'zip': '10001'}

Example (using | operator – Python 3.9+):

person = {"name": "John", "age": 30}
address = {"city": "New York", "zip": "10001"}

# Merging two dictionaries using the | operator
merged_dict = person | address
print(merged_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'zip': '10001'}

9. Dictionary Comprehension

Similar to list comprehensions, you can create dictionaries using dictionary comprehensions. It allows you to build dictionaries from an iterable.

Example:

# Creating a dictionary with keys as numbers and values as their squares
squares = {x: x**2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

10. Default Dictionary

The defaultdict from the collections module provides a dictionary that returns a default value if a key does not exist, rather than raising a KeyError.

Example:

from collections import defaultdict

# Creating a defaultdict with default value as 0
counter = defaultdict(int)

# Adding values to the dictionary
counter["apple"] += 1
counter["banana"] += 2

print(counter)  # Output: defaultdict(<class 'int'>, {'apple': 1, 'banana': 2})

Summary:

  • Dictionaries are unordered collections of key-value pairs.
  • You can create dictionaries with different types of keys and values.
  • You can access, add, modify, and remove dictionary elements using keys.
  • Dictionaries support various operations like merging, nested structures, and comprehensions.
  • Methods like keys(), values(), and items() allow you to interact with dictionary data in a useful way.
Leave a Reply 0

Your email address will not be published. Required fields are marked *