Your Page Title
🔍

    How to Create a Dictionary in Python

    What is a dictionary in Python?

    • An unordered collection of items is a dictionary.
    • Each item is a key-value pair such that:
      • The key is unique.
      • The value is associated with that key and can be any data type.

    Creating a Dictionary

    1. Using Curly Braces ({})

    The most common way to create a dictionary is by enclosing key-value pairs within curly braces.

    # Example
    my_dict = {
        "name": "Alice",
        "age": 25,
        "city": "New York"
    }
    print(my_dict)

    2. Using the dict() Constructor

    You can also create a dictionary using the built-in dict() constructor.

    # Example
    my_dict = dict(name="Alice", age=25, city="New York")
    print(my_dict)

    Note: When using dict(), keys must be valid identifiers (like variable names).

    3. Creating an Empty Dictionary

    You can create an empty dictionary to add key-value pairs later.

    # Example
    empty_dict = {}
    print(empty_dict)  # Output: {}

    Adding Key-Value Pairs

    You can add a key-value pair by assigning a value to a new key.

    my_dict = {}
    my_dict["name"] = "Alice"
    my_dict["age"] = 25
    print(my_dict)  # Output: {'name': 'Alice', 'age': 25}

    Accessing Values

    You can access the value of a specific key using square brackets or the get() method.

    # Using square brackets
    print(my_dict["name"])  # Output: Alice
    
    # Using get()
    print(my_dict.get("age"))  # Output: 25

    Note: If the key doesn’t exist, my_dict[key] raises a KeyError, whereas my_dict.get(key) returns None.

    Common Dictionary Operations

    1. Updating Values

    You can update the value of an existing key.

    my_dict["age"] = 30
    print(my_dict)  # Output: {'name': 'Alice', 'age': 30}

    2. Removing Items

    Use del, pop(), or popitem() to remove items:

    • del: Removes a specific key-value pair.
    del my_dict["age"]
    print(my_dict)  # Output: {'name': 'Alice'}
    • pop(): Removes a key and returns its value.
    age = my_dict.pop("age")
    print(age)        # Output: 25
    print(my_dict)    # Output: {'name': 'Alice'}
    • popitem(): Removes the last inserted key-value pair.
    item = my_dict.popitem()
    print(item)  # Output: ('city', 'New York')

    Iterating Through a Dictionary

    You can loop through keys, values, or both:

    # Loop through keys
    for key in my_dict:
        print(key)
    
    # Loop through values
    for value in my_dict.values():
        print(value)
    
    # Loop through key-value pairs
    for key, value in my_dict.items():
        print(f"{key}: {value}")

    Dictionary Methods

    Here are some useful dictionary methods:

    • keys(): Returns all keys.
    • values(): Returns all values.
    • items(): Returns all key-value pairs.
    • clear(): Removes all items.
    • update(): Updates the dictionary with another dictionary.
    my_dict.update({"gender": "female"})
    print(my_dict)  # Output: {'name': 'Alice', 'age': 25, 'gender': 'female'}

    Nested Dictionaries

    Dictionaries can contain other dictionaries.

    nested_dict = {
        "person1": {"name": "Alice", "age": 25},
        "person2": {"name": "Bob", "age": 30}
    }
    print(nested_dict["person1"]["name"])  # Output: Alice

    Key Characteristics of Dictionaries

    • Keys must be immutable (e.g., strings, numbers, tuples).
    • Values can be of any data type.
    • Dictionaries are unordered (Python 3.6+ maintains insertion order).

    Complete Example

    # Create a dictionary
    student = {
        "name": "John",
        "age": 20,
        "courses": ["Math", "Science"]
    }
    
    # Access values
    print(student["name"])  # Output: John
    
    # Add a new key-value pair
    student["grade"] = "A"
    
    # Update an existing key
    student["age"] = 21
    
    # Remove a key-value pair
    del student["grade"]
    
    # Loop through dictionary
    for key, value in student.items():
        print(f"{key}: {value}")