Python Dictionaries


Python Dictionaries

A dictionary in Python is an unordered, mutable collection of key-value pairs. Each key in a dictionary is associated with a value, and you can retrieve, update, or delete a value by referencing its key. Keys in a dictionary must be unique and immutable (e.g., strings, numbers, tuples), while the values can be of any type.

Key Features of Dictionaries:

  1. Unordered: Unlike lists and tuples, dictionaries do not maintain any order for their elements.
  2. Mutable: You can modify the dictionary by adding, updating, or deleting key-value pairs.
  3. Key-Value Pairs: Each element in the dictionary is stored as a key-value pair.
  4. Keys Must Be Unique: No two keys in a dictionary can be the same.
  5. Fast Lookup: Dictionaries offer fast lookups by key.

Dictionary Syntax:

Dictionaries are defined using curly braces {}, with key-value pairs separated by a colon :.

# Creating a dictionary my_dict = {"name": "John", "age": 30, "city": "New York"}

Example: Creating a Dictionary

# A simple dictionary person = { "name": "Alice", "age": 28, "profession": "Engineer" } print(person) # Output: {'name': 'Alice', 'age': 28, 'profession': 'Engineer'}

Accessing Dictionary Values:

You can access a value by referencing its corresponding key.

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

If you try to access a key that doesn’t exist, Python will raise a KeyError. To avoid this, you can use the .get() method, which returns None (or a default value) if the key is not found.

# Using .get() to safely access a value print(person.get("profession")) # Output: Engineer print(person.get("salary")) # Output: None

Adding and Updating Elements:

You can add new key-value pairs or update existing ones by assigning values to a key.

# Adding a new key-value pair person["salary"] = 80000 print(person) # Output: {'name': 'Alice', 'age': 28, 'profession': 'Engineer', 'salary': 80000} # Updating an existing key-value pair person["age"] = 29 print(person) # Output: {'name': 'Alice', 'age': 29, 'profession': 'Engineer', 'salary': 80000}

Removing Elements:

You can remove elements from a dictionary using several methods:

  • pop(key): Removes the key-value pair for the specified key and returns its value.
  • popitem(): Removes and returns the last inserted key-value pair (only in Python 3.7+).
  • del: Removes the key-value pair by key.
  • clear(): Removes all key-value pairs from the dictionary.
# Removing a specific key-value pair using pop() person.pop("salary") print(person) # Output: {'name': 'Alice', 'age': 29, 'profession': 'Engineer'} # Removing an element using del del person["age"] print(person) # Output: {'name': 'Alice', 'profession': 'Engineer'} # Clearing the entire dictionary person.clear() print(person) # Output: {}

Dictionary Methods:

  1. .keys(): Returns a list-like view of all the keys in the dictionary.
  2. .values(): Returns a list-like view of all the values in the dictionary.
  3. .items(): Returns a list-like view of all the key-value pairs in the dictionary.
person = {"name": "Alice", "age": 28, "profession": "Engineer"} # Getting all keys print(person.keys()) # Output: dict_keys(['name', 'age', 'profession']) # Getting all values print(person.values()) # Output: dict_values(['Alice', 28, 'Engineer']) # Getting all key-value pairs print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 28), ('profession', 'Engineer')])

Looping Through a Dictionary:

You can iterate over the keys, values, or key-value pairs in a dictionary using loops.

# Iterating through the keys for key in person: print(key) # Output: # name # age # profession # Iterating through key-value pairs for key, value in person.items(): print(f"{key}: {value}") # Output: # name: Alice # age: 28 # profession: Engineer

Checking for Keys:

You can check whether a key exists in the dictionary using the in keyword.

# Check if a key exists in the dictionary if "name" in person: print("Key 'name' exists.") else: print("Key 'name' does not exist.") # Output: Key 'name' exists.

Dictionary Comprehension:

You can create dictionaries using dictionary comprehensions, which are concise ways to build a dictionary.

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

Nesting Dictionaries:

Dictionaries can contain other dictionaries, creating a nested structure.

# Nested dictionary employees = { "emp1": {"name": "Alice", "position": "Manager"}, "emp2": {"name": "Bob", "position": "Engineer"}, } print(employees["emp1"]["name"]) # Output: Alice

Example: Dictionary as a Phone Book

# Example: Dictionary as a phone book phone_book = { "John": "+1-202-555-0198", "Alice": "+1-202-555-0123", "Bob": "+1-202-555-0176" } # Lookup a phone number by name print(phone_book["Alice"]) # Output: +1-202-555-0123

Summary:

  • A dictionary is a collection of key-value pairs.
  • Keys must be unique and immutable, but values can be of any type.
  • Dictionaries are useful when you need to associate and retrieve values by key, such as storing a phone book, mapping IDs to values, or building data structures like trees or graphs.