Python Dictionaries: Your Secret Weapon for Data Agility

Python dictionaries are a fundamental and versatile data structure. They allow you to store data in key value pairs, providing an efficient way to organize and manage information.

A dictionary is like a real world dictionary where you look up a word (“Key”) to find its definition (“Value”). In Python:

  • Key: A unique identifier for a piece of data. Keys must be immutable (e.g., strings, numbers, tuples).

  • Value: The data associated with a key. Values can be of any data type (e.g., strings, numbers, lists, even other dictionaries).

Key Characteristics of a Dictionary:

  • Mutable: You can add, modify, or remove key-value pairs after a dictionary is created.

  • Unique Keys: A dictionary cannot contain duplicate keys. If you try to assign a value to an existing key, the old value will be overwritten.

  • Values: In dictionary multiple different keys can have the same value.

  • Ordered: Starting with Python 3.7, dictionary preserve the means that items are stored in the order they were added. In python 3.6 and earlier, dictionaries are unordered

Creating Dictionaries:

You can create dictionaries using curly braces {} :

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}
print(student)

Accessing Values:

You access values using their corresponding keys within square brackets [] :

student = {"name": "Alice", "age": 20}
print(student["name"])  # Output: Alice
print(student["age"])    # Output: 20

#Accessing a value using get()
print(student.get("name")) #Output: Alice
print(student.get("major")) #Output: None
print(student.get("major", "Unknown")) #Output: Unknown

Modifying Dictionaries:

  • Adding/Updating: To add a new key-value pair or update an existing one:

      student = {"name": "Alice", "age": 20}
      student["major"] = "Computer Science"  # Add a new key-value pair
      student["age"] = 21  # Update the value for "age"
      print(student)
    
  • Removing:

    • pop(key): Removes the key and returns its value. Raises a KeyError if the key is not found.

        student = {"name": "Alice", "age": 20, "major": "Computer Science"}
        age = student.pop("age")
        print(age) # Output: 20
        print(student) #Output:{'name': 'Alice', 'major': 'Computer Science'}
      
    • popitem(): Removes and returns an arbitrary (key, value) pair. (Removes the last inserted item in Python 3.7+).

        student = {"name": "Alice", "age": 20, "major": "Computer Science"}
        item = student.popitem()
        print(item)    # Output: ('major', 'Computer Science') (or another pair)
        print(student)
      
    • del: Deletes a key-value pair. Raises a KeyError if the key is not found.

        student = {"name": "Alice", "age": 20, "major": "Computer Science"}
        del student["age"]
        print(student)   # Output: {'name': 'Alice', 'major': 'Computer Science'}
      
    • clear(): Removes all items from the dictionary, leaving it empty.

        student = {"name": "Alice", "age": 20, "major": "Computer Science"}
        student.clear()
        print(student)  # Output: {}
      
    • Iterating Through Dictionaries:

      You can iterate over dictionaries in various ways:

      • Iterating over keys (default):

          student = {"name": "Alice", "age": 20, "major": "Computer Science"}
          for key in student:
              print(key)  # Output: name, age, major
        
      • Iterating over values:

          student = {"name": "Alice", "age": 20, "major": "Computer Science"}
          for value in student.values():
              print(value)  # Output: Alice, 20, Computer Science
        
      • Iterating over key-value pairs:

          student = {"name": "Alice", "age": 20, "major": "Computer Science"}
          for key, value in student.items():
              print(f"{key}: {value}")
              # Output:
              # name: Alice
        

Some Dictionaries Methods:

Here are some popular methods used in dictionaries that can make your coding experience even better!

  • keys(): Gives you a view of all the keys in the dictionary.

  • values(): Gives you a view of all the values in the dictionary.

  • items(): Gives you a view of all the (key, value) pairs as tuples.

  • get(key, default): Gets the value for the given key. If the key isn't there, it returns the default value (or None if no default is given).

  • update(other_dict): Adds key-value pairs from other_dict to the dictionary. It replaces values for existing keys and adds new keys.

12
Subscribe to my newsletter

Read articles from Aryan Srivastava directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aryan Srivastava
Aryan Srivastava