Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Dictionary Operations and Usage

Tech 1

Dictionary Initialization

A dictionary is a mutable mapping type that stores data as key-value pairs within curly braces {}. It is optimized for fast data lookup.

# Initializing using various methods
inventory = dict(apples=10, oranges=5, bananas=8)
print(inventory)

squares = {n: n*n for n in range(2, 9, 2)}
print(squares)

pairs = dict([('x', 1), ('y', 2)])
print(pairs)

# Empty dictionaries
empty_1 = {}
empty_2 = dict()

Keys must be of an immutable type (like strings or numbers) and must be unique. Assigning a value to an existing key overwrites the previous value.

data = {"id": 101, "status": "active", "id": 102}
print(data) # Output will show id: 102

Common Dictionary Operations

Assigning a value to a key acts as an insertion if the key is absent, or an update if it exists.

# Inserting and Updating
catalog = {"laptop": 999, "mouse": 25, "keyboard": 50}
catalog["monitor"] = 200  # Insert
catalog["mouse"] = 30     # Update
print(catalog)

# Removing a specific key-value pair
removed_price = catalog.pop("keyboard")
print(f"Removed: {removed_price}")

# Accessing keys, values, and items
print(catalog.keys())
print(catalog.values())
print(catalog.items())

# Safe value retrieval
price = catalog.get("laptop")
missing = catalog.get("webcam") # Returns None instead of KeyError

# Removing the last inserted item
last_item = catalog.popitem()
print(f"Popped: {last_item}")

# Checking size and clearing
print(f"Size: {len(catalog)}")
catalog.clear()
print(catalog)

Nested Dictionaries

Values within a dictionary can be other dictionaries, allowing for complex hierarchical data structures.

company = {
    "dept_a": {"manager": "Alice", "headcount": 12},
    "dept_b": {"manager": "Bob", "headcount": 8}
}

manager_b = company["dept_b"]["manager"]
print(manager_b)

Iterating Over Dictionaries

Dictionaries do not support numeric indexing; elements are accessed via their keys. Attempting to access a non-existent key directly (e.g., d[key]) raises a KeyError.

config = {"theme": "dark", "font": 14, "autosave": True}

# Iterating over keys directly
for setting in config:
    print(f"Key: {setting}, Value: {config[setting]}")

# Iterating over keys explicitly
for k in config.keys():
    print(k)

# Iterating over values
for v in config.values():
    print(v)

# Iterating over key-value pairs
for key, val in config.items():
    print(f"{key} -> {val}")

Key Characteristics

  • Capable of storing multiple entries of varying data types.
  • Data is stored as unique key-value mappings; duplicate keys overwrite previous entries.
  • Elements are accessed via keys rather than sequential index positions.
  • Mutable: entries can be added, modified, or removed after creation.
  • Iterable using for loops, but not compatible with while loops due to the lack of index support.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.