Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Dictionaries

A dictionary in Python is an unordered collection of key-value pairs, where each key must be unique. Dictionaries are mutable, which means you can add, remove, or modify items after the dictionary is created. In this tutorial, we'll go through some common operations you can perform on dictionaries.

  • Creating a dictionary:

You can create a dictionary using curly braces {} and separating keys and values with a colon :. To create an empty dictionary, use empty curly braces or the dict() constructor.

# Creating a dictionary with some items
person = {
    "name": "Alice",
    "age": 30,
    "occupation": "Engineer"
}

# Creating an empty dictionary
empty_dict1 = {}
empty_dict2 = dict()
  • Accessing values:

You can access the value associated with a key using square brackets [] or the get() method.

person = {
    "name": "Alice",
    "age": 30,
    "occupation": "Engineer"
}

# Accessing values using square brackets
print(person["name"])  # Output: Alice

# Accessing values using the get() method
print(person.get("age"))  # Output: 30

If you use square brackets and the key doesn't exist, you'll get a KeyError. The get() method returns None by default if the key is not found, but you can provide a default value as a second argument.

print(person["city"])  # Raises KeyError

print(person.get("city"))  # Output: None
print(person.get("city", "Unknown"))  # Output: Unknown
  • Modifying values and adding new items:

You can modify the value associated with a key or add a new key-value pair by assigning a value using the key in square brackets.

person = {
    "name": "Alice",
    "age": 30,
    "occupation": "Engineer"
}

# Modifying a value
person["age"] = 31

# Adding a new key-value pair
person["city"] = "New York"

print(person)
# Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer', 'city': 'New York'}
  • Deleting items:

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

person = {
    "name": "Alice",
    "age": 30,
    "occupation": "Engineer"
}

# Deleting an item using del
del person["age"]

# Deleting an item using pop()
occupation = person.pop("occupation")

print(person)  # Output: {'name': 'Alice'}
  • Iterating through a dictionary:

You can iterate through a dictionary's keys, values, or key-value pairs using the keys(), values(), or items() methods, respectively.

person = {
    "name": "Alice",
    "age": 30,
    "occupation": "Engineer"
}

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

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

# Iterating through key-value pairs
for key, value in person.items():
    print(key, value)
  1. Creating dictionaries in Python:

    • Description: Dictionaries in Python are created using curly braces {} and key-value pairs.
    • Code:
    # Creating a dictionary
    person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
    
  2. Accessing and modifying dictionary elements in Python:

    • Description: Access and modify values in a dictionary using keys.
    • Code:
    # Accessing dictionary elements
    name = person['name']
    
    # Modifying dictionary elements
    person['age'] = 26
    
  3. Dictionary methods and operations in Python:

    • Description: Dictionaries provide various methods for common operations.
    • Code:
    # Dictionary methods
    keys = person.keys()
    values = person.values()
    items = person.items()
    
    # Check if a key is present
    is_city_present = 'city' in person
    
  4. Iterating over keys, values, and items in a dictionary:

    • Description: Iterate over keys, values, or key-value pairs in a dictionary.
    • Code:
    # Iterating over keys
    for key in person:
        print(key)
    
    # Iterating over values
    for value in person.values():
        print(value)
    
    # Iterating over items (key-value pairs)
    for key, value in person.items():
        print(f"{key}: {value}")
    
  5. Merging and updating dictionaries in Python:

    • Description: Combine or update dictionaries.
    • Code:
    # Merging dictionaries
    additional_info = {'gender': 'Female', 'occupation': 'Engineer'}
    merged_person = {**person, **additional_info}
    
    # Updating dictionary
    person.update({'age': 27, 'city': 'San Francisco'})
    
  6. Nested dictionaries and dictionary comprehensions in Python:

    • Description: Create nested dictionaries and use comprehensions.
    • Code:
    # Nested dictionaries
    contacts = {'Alice': {'phone': '123-456-7890', 'email': 'alice@example.com'},
                'Bob': {'phone': '987-654-3210', 'email': 'bob@example.com'}}
    
    # Dictionary comprehension
    squares = {num: num**2 for num in range(1, 6)}
    
  7. Common use cases for dictionaries in Python:

    • Description: Dictionaries are commonly used for data storage, mapping, and configuration settings.
    • Code:
    # Use case: Data storage
    person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
    
    # Use case: Mapping
    fruit_prices = {'apple': 1.0, 'banana': 0.75, 'orange': 1.25}
    
    # Use case: Configuration settings
    config = {'debug_mode': True, 'max_connections': 100}
    
  8. Error handling and avoiding key errors in Python dictionaries:

    • Description: Use get method or default argument to handle potential key errors.
    • Code:
    # Avoiding key errors with get method
    age = person.get('age', 'N/A')
    
    # Avoiding key errors with default argument
    occupation = person.setdefault('occupation', 'Unknown')