Python Dictionaries

A dictionary in Python is an unordered, mutable, and indexed collection of key-value pairs. It is used to store data values where each key is unique and associated with a specific value. Dictionaries are implemented as hash tables, making operations like lookup, insertion, and deletion very efficient.

 

Key Features of Dictionaries


  1. Key-Value Pairs: Each element in a dictionary is a key-value pair: {key: value}.
  2. Keys Must Be Unique: Duplicate keys are not allowed; the latest value overwrites the previous one.
  3. Keys Must Be Immutable: Keys must be hashable types like strings, numbers, or tuples (containing only immutable elements).
  4. Values Can Be Any Type: Values can be of any data type and may be duplicated.

 

Creating a Dictionary


  1. Using Curly Braces {}:
    my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
    
  2. Using the dict() Constructor:
    my_dict = dict(name='Alice', age=25, city='New York')
    
  3. Empty Dictionary:
    empty_dict = {}
    

 

Accessing Dictionary Elements


Accessing Values

  1. Using Keys:
    print(my_dict['name'])  # Output: Alice
    

    If the key doesn’t exist, it raises a KeyError.

  2. Using get():
    print(my_dict.get('age'))       # Output: 25
        print(my_dict.get('country', 'USA'))  # Output: USA (default value)
    

 

Adding and Updating Elements


  1. Adding a New Key-Value Pair:
    my_dict['country'] = 'USA'
    
  2. Updating a Value:
    my_dict['age'] = 30
    

 

Removing Elements


  1. Using pop(): Removes a key and returns its value. Raises KeyError if the key is not found.
    age = my_dict.pop('age')
    print(age)  # Output: 25
    
  2. Using popitem(): Removes and returns the last inserted key-value pair (for Python 3.7+).
    key, value = my_dict.popitem()
    print(key, value)
    
  3. Using del: Deletes a key-value pair or the entire dictionary.
    del my_dict['name']
    del my_dict  # Deletes the entire dictionary
    
  • Using clear(): Removes all elements.
    my_dict.clear()
    

 

Dictionary Operations


  1. Check if a Key Exists
    if 'name' in my_dict:
        print("Key exists!")
    
  2. Iterating Through a Dictionary
    • Keys:
      for key in my_dict:
          print(key)
      
    • Values:
      for value in my_dict.values():
          print(value)
      
    • Key-Value Pairs:
      for key, value in my_dict.items():
          print(f"{key}: {value}")
      

 

Dictionary Methods


Method Description
get(key, default)
Returns the value for a key, or a default value if the key does not exist.
keys() Returns a view object of all keys.
values() Returns a view object of all values.
items()
Returns a view object of all key-value pairs as tuples.
update(other_dict)
Updates the dictionary with key-value pairs from another dictionary or iterable.
pop(key) Removes the key and returns its value.
popitem()
Removes and returns the last inserted key-value pair.
clear() Removes all elements from the dictionary.
copy() Returns a shallow copy of the dictionary.

 

Examples of Usage


  • Merging Dictionaries
    dict1 = {'a': 1, 'b': 2}
    dict2 = {'b': 3, 'c': 4}
    dict1.update(dict2)  # {'a': 1, 'b': 3, 'c': 4}
    
  • Dictionary Comprehension
    squares = {x: x**2 for x in range(5)}
    print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
    
  • Counting Elements
    from collections import Counter
    words = ['apple', 'banana', 'apple']
    count = Counter(words)
    print(count)  # Output: {'apple': 2, 'banana': 1}
    

 

Advantages of Dictionaries


  1. Fast Lookups: Optimized for retrieving values by keys.
  2. Flexible Values: Can store any data type as values.
  3. Dynamic: Can grow or shrink dynamically.
  4. Readable: Key-value format makes the data easy to interpret.

 

Disadvantages of Dictionaries


  1. Unordered (Prior to Python 3.7): Does not maintain the insertion order.
  2. Memory Overhead: Consumes more memory than lists or tuples.
  3. Immutable Keys Only: Cannot use mutable types like lists as keys.

 

Dictionaries are an essential data structure for scenarios requiring fast lookups and mappings between keys and values.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *