Dictionaries

DATA STRUCTURES


Python Dictionaries

A dictionary in Python is an unordered 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.

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}