All categories

    Dictionaries

    Key/value pairs, iteration, and updates.

    01Create and access

    main.py
    person = {"name": "Ada", "age": 36}
    print(person["name"])
    print(person.get("city", "Unknown"))
    Output
    Ada
    Unknown

    02Add and update

    main.py
    d = {"a": 1, "b": 2}
    d["c"] = 3
    d["a"] = 10
    print(d)
    Output
    {'a': 10, 'b': 2, 'c': 3}

    03Iterate over items

    main.py
    prices = {"apple": 1.2, "bread": 2.5, "milk": 1.0}
    for item, price in prices.items():
        print(f"{item}: ${price:.2f}")
    Output
    apple: $1.20
    bread: $2.50
    milk: $1.00

    04Keys, values, length

    main.py
    d = {"x": 1, "y": 2, "z": 3}
    print(list(d.keys()))
    print(list(d.values()))
    print(len(d))
    Output
    ['x', 'y', 'z']
    [1, 2, 3]
    3

    05Dict comprehension

    main.py
    squares = {n: n * n for n in range(1, 6)}
    print(squares)
    Output
    {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}