Dictionaries

DATA STRUCTURES


Python Dictionaries

A dictionary in Python is an Ordered(after python 3.7) collection of key-value pairs. It is optimized for fast lookups and allows easy modification. Unlike lists, dictionaries use keys to access values, making them ideal for mappings.

How are Dictionaries implemented in python ?

A dictionary in Python stores key–value pairs.
Internally, it uses a hash table (or hashmap) to provide O(1) average-time complexity for lookups, insertions, and deletions.

Each key is passed through a hash function (using Python’s built-in hash()), which converts the key into a fixed-size integer value called a hash.
This hash determines where the key–value pair is placed in the hash table.

NOTE: Python Dictionaries would be unordered if they were only based on hash tables. But we know that they are ordered. This is achieved by using a internal compact array that keeps track of the insertion order, while the hash table ensures efficient lookups, insertions, and deletions.

Dictionary Operations (dict)

Good for: Key-value pairs, fast lookups, unordered, mutable

Basic Operations

  • dict[key] = value → Add or update a key-value pair
  • dict.get(key, default) → Get value (default if not found)
  • dict.keys() → Get all keys
  • dict.values() → Get all values
  • dict.items() → Get all key-value pairs
  • dict.pop(key, default) → Remove and return value
  • dict.popitem() → Remove and return last inserted pair
  • dict.update(other_dict) → Merge another dictionary
  • dict.clear() → Remove all items
  • dict.copy() → Create a shallow copy
  • dict.setdefault(key, default) → Get value or insert default

Example:

# Creating a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}

# Accessing values
print(person["name"])  # Output: Alice

# Using get method
print(person.get("age", 30))  # Output: 25
print(person.get("gender", "Not specified"))  # Output: Not specified

# Updating values
person["age"] = 26

# Adding a new key-value pair
person["job"] = "Engineer"

# Removing a key
removed_value = person.pop("city")

# Iterating through keys and values
for key, value in person.items():
    print(key, ":", value)

Dictionary Comprehension

Dictionary comprehension provides a concise way to create dictionaries.

# Creating a dictionary from a list
squares = {x: x*x for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Conversion

  • dict(list_of_tuples) → Convert list of tuples to dictionary

Example:

# Converting list of tuples to dictionary
pairs = [("one", 1), ("two", 2), ("three", 3)]
num_dict = dict(pairs)
print(num_dict)  # Output: {'one': 1, 'two': 2, 'three': 3}