Python Dictionaries: Complete Mastery of Hash Mappings & Dict Methods

A dictionary (dict) is Python's implementation of an associative array or hash table. It stores associations between unique keys and their corresponding values. Dictionaries are optimized for lightning-fast O(1) average-time complexity lookups, insertions, and deletions, making them the backbone of JSON parsing, web APIs, database models, and object namespaces.


1. Creating Dictionaries & Key Requirements

Dictionaries are defined with curly braces {} using key: value pairs:

# Creating a dictionary:
student = {
    "roll_no": 105,
    "name": "Kavita Rao",
    "course": "BCA",
    "semester": 4,
    "cgpa": 9.15,
    "skills": ["Python", "SQL", "HTML"]
}

print("Student Name:", student["name"])
print("First Skill: ", student["skills"][0])

Golden Rule for Dictionary Keys: Keys must be immutable and hashable (e.g., strings, numbers, tuples). Values can be of any data type (including lists, sets, or nested dictionaries).


2. Safely Accessing Values: get() vs []

Using bracket syntax on a non-existent key crashes your code with a KeyError. Always prefer .get():

user = {"username": "amit99", "role": "editor"}

# Risky bracket access:
# email = user["email"]  # Raises KeyError: 'email'!

# Safe access with get():
email = user.get("email")                 # Returns None
status = user.get("status", "Active")    # Returns fallback 'Active'

print("Email:", email)
print("Status:", status)

3. Adding, Updating & Deleting Elements

employee = {"id": 1001, "name": "Suresh", "dept": "IT"}

# Add or update:
employee["salary"] = 65000       # Adds new key 'salary'
employee["dept"] = "Engineering" # Updates existing key 'dept'

# update() method: Merge multiple pairs:
employee.update({"city": "Noida", "shift": "Day"})

# Removing elements:
salary = employee.pop("salary")  # Removes 'salary' and returns 65000
del employee["shift"]            # Deletes key 'shift'

4. Iterating Over Dictionaries: keys(), values(), items()

Dictionary view objects provide dynamic windows into dictionary contents:

inventory = {"Laptops": 25, "Keyboards": 80, "Monitors": 45}

# 1. Iterate over keys and values together (Most Common!):
for item, count in inventory.items():
    print(f"Product: {item:<12} | In Stock: {count}")

# 2. Iterate keys only:
for item in inventory.keys():
    print("Item:", item)

# 3. Sum all values directly:
total_inventory = sum(inventory.values())
print("Total Inventory Items:", total_inventory)  # 150

5. Modern Dictionary Merging (Python 3.9+ Union Operator |)

Python 3.9 introduced the union operator (|) and update operator (|=) for dictionaries:

default_config = {"theme": "light", "notifications": True, "timeout": 30}
user_config = {"theme": "dark", "timeout": 60}

# Merge with | (right-side values overwrite left-side!):
final_config = default_config | user_config
print("Merged Config:", final_config)
# {'theme': 'dark', 'notifications': True, 'timeout': 60}

Frequently Asked Questions (FAQ)

Can a dictionary have duplicate keys?

No. Dictionary keys must be strictly unique. If you define a duplicate key, the last assigned value silently overwrites the previous value.

What is the difference between setdefault() and get()?

get(key, default) returns the default value without modifying the dictionary. In contrast, setdefault(key, default) returns the value, and if the key was missing, it actually inserts the key with the default value into the dictionary!
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!