Dictionary in Python

Dictionaries in Python are versatile data structures that store key-value pairs. Python provides numerous built-in functions and methods to manipulate dictionaries efficiently. Below is a comprehensive overview of dictionary functions in Python.

Creating Dictionaries

  • dict() - Creates a new dictionary
  • dict.fromkeys() - Creates a new dictionary with specified keys and optional value

Basic Dictionary Operations

  • len() - Returns the number of key-value pairs in the dictionary
  • in - Tests if a key exists in the dictionary
  • not in - Tests if a key does not exist in the dictionary
  • del - Removes a key-value pair from the dictionary

Accessing Dictionary Elements

  • get() - Returns the value for a key, or a default value if the key is not found
  • setdefault() - Returns the value of a key if it exists; otherwise, inserts the key with a specified value and returns that value
  • [] - Accesses or assigns a value using key (raises KeyError if key not found)

Dictionary Modification Methods

  • update() - Updates the dictionary with elements from another dictionary or key-value pairs
  • clear() - Removes all items from the dictionary
  • pop() - Removes and returns an item with the specified key
  • popitem() - Removes and returns the last inserted key-value pair

Dictionary View Methods

  • keys() - Returns a view object containing all keys
  • values() - Returns a view object containing all values
  • items() - Returns a view object containing all key-value pairs as tuples

Dictionary Iteration and Comprehension

  • Dictionary comprehension - Creates dictionaries using a compact syntax
  • Iterating through keys, values, or items - Various techniques for dictionary traversal

Dictionary Comparison and Testing

  • ==, != - Tests if two dictionaries have the same key-value pairs
  • copy() - Creates a shallow copy of the dictionary

Dictionary Utilities

  • sorted() - Returns a new sorted list of dictionary keys
  • any() - Returns True if any key in the dictionary is True
  • all() - Returns True if all keys in the dictionary are True
  • max() - Returns the largest key in the dictionary
  • min() - Returns the smallest key in the dictionary

Dictionary Merging (Python 3.9+)

  • | - Union operator for merging dictionaries
  • |= - Update operator for in-place dictionary union

Special Dictionary Types

  • defaultdict - Dictionary subclass that calls a factory function to supply missing values
  • OrderedDict - Dictionary subclass that remembers the order entries were added
  • Counter - Dictionary subclass for counting hashable objects

Dictionary functions and methods in Python provide powerful tools for managing collections of key-value pairs. They enable efficient data storage, retrieval, and manipulation for a wide range of programming applications. Understanding these functions allows developers to effectively leverage dictionaries as a fundamental data structure in Python.