Your Page Title
🔍

    Python Dictionary

    A dictionary is a Python in-built data structure where it allows the storing of data in pairs of key-values. Dictionaries are, therefore very versatile and applied in large scales to jobs that would require the fastest look-up, storage or association of data.

    Key Features of a Python Dictionary:

    1. Unordered: Dictionaries in Python 3.7+ maintain the insertion order of items, but are not indexed like lists and cannot be accessed by an index.
    2. Mutable: Items may be added, changed or deleted after the dictionary has been created.
    3. Key-value pairs: Every item within a dictionary is stored in the form of a key: value pair.
    4. Unique Keys: Keys in a dictionary must be unique and immutable (strings, numbers, tuples, etc.).
    5. Dynamic Size: Dictionaries can grow or shrink dynamically as items are added or removed.

    Syntax to Create a Dictionary:

    You can create a dictionary using curly braces {} or the dict() constructor.

    Example:

    # Using curly braces
    my_dict = {"name": "Alice", "age": 25, "city": "New York"}
    # Using the dict() constructor
    my_dict2 = dict(name="Bob", age=30, city="San Francisco")

    Accessing Values in a Dictionary:

    You can retrieve a value using its corresponding key.

    Example:

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

    To avoid errors when a key does not exist, you can use the get() method:

    print(my_dict.get("country", "Not Found")) # Output: Not Found

    Adding or Updating Items:

    • To add a new key-value pair:
    my_dict["country"] = "USA"
    • To update an existing key:
    my_dict["age"] = 26

    Removing Items:

    • Using pop() (removes a key and returns its value):
    removed_value = my_dict.pop("city") # Removes "city"
    • Using del (deletes a key-value pair):
    del my_dict["name"]
    • Using clear() (removes all items):
    my_dict.clear()

    Iterating Through a Dictionary:

    1. Keys: Use for key in my_dict.
    for key in my_dict:
       print(key)

    2. Values: Use my_dict.values().

    for value in my_dict.values():
       print(value)

    3. Key-Value Pairs: Use my_dict.items().

    for key, value in my_dict.items():
        print(f"{key}: {value}")

    Dictionary Methods:

    Here are some useful methods:

    MethodDescription
    clear()Removes all elements from the dictionary.
    copy()Returns a shallow copy of the dictionary.
    get(key, [val])Returns the value of the key; if key doesn’t exist, returns val (default is None).
    keys()Returns a view object with all the keys.
    values()Returns a view object with all the values.
    items()Returns a view object with all the key-value pairs.
    pop(key)Removes the item with the specified key and returns its value.
    popitem()Removes and returns the last inserted key-value pair as a tuple.
    update(dict2)Updates the dictionary with key-value pairs from another dictionary or iterable of pairs.

    Example Usage:

    # Creating a dictionary
    student = {"name": "John", "age": 20, "major": "Computer Science"}
    
    # Accessing elements
    print(student["name"])         # Output: John
    print(student.get("gpa", 4.0)) # Output: 4.0 (default value)
    
    # Adding/updating elements
    student["gpa"] = 3.8
    student["age"] = 21
    
    # Iterating
    for key, value in student.items():
       print(f"{key}: {value}")
    
    # Removing elements
    student.pop("major")
    print(student) # Output: {'name': 'John', 'age': 21, 'gpa': 3.8}