PythonProgramming Basics

Mastering Python Dictionaries: The Power of Key-Value Pairs

TT
TopicTrick
Mastering Python Dictionaries: The Power of Key-Value Pairs

Introduction to Python Dictionaries

In Python, a Dictionary is one of the most essential and widely used data structures. Unlike lists or tuples that use numerical indexes, dictionaries use Keys to map to specific Values.

Think of it like a real-world dictionary: you look up a Word (the Key) to find its Definition (the Value).

Core Concept

Dictionaries are Unordered, Mutable, and Key-Indexed. Every key in a dictionary must be unique and immutable (like a string or a number).

    Creating Dictionaries

    There are multiple ways to initialize a dictionary in Python, depending on your needs.

    1. Simple Literals

    The most common way is using curly braces {} with key-value pairs separated by colons.

    python
    1# Create a dictionary of counts 2counts = {'one': 1, 'two': 2, 'three': 3} 3 4# Create an empty dictionary 5empty_dict = {}

    2. Using the dict() Constructor

    You can also build a dictionary from a list of tuples or keyword arguments.

    python
    1# From a list of tuples 2pairs = [('name', 'TopicTrick'), ('type', 'Blog')] 3site_info = dict(pairs) 4 5# Using keyword arguments 6user = dict(name='Dev', age=25)

    Accessing and Modifying Data

    Accessing Values

    You can retrieve a value using its key in square brackets or the .get() method.

    Why use .get()?

    Using `dict[key]` will raise an error if the key doesn't exist. `dict.get(key)` will safely return `None` (or a default value) instead.

      python
      1data = {'Dublin': 'Ireland', 'London': 'UK'} 2 3# Trivial access 4print(data['Dublin']) # Ireland 5 6# Safe access with default 7print(data.get('Paris', 'Unknown City')) # Unknown City

      Adding and Updating

      Dictionaries are mutable, so you can add new pairs or update existing ones easily.

      python
      1user = {'name': 'Alice'} 2 3# Add a new key 4user['age'] = 30 5 6# Update using .update() 7user.update({'email': 'alice@example.com', 'age': 31})

      Essential Dictionary Methods

      MethodDescription
      keys()Returns a view of all keys
      values()Returns a view of all values
      items()Returns a view of all key-value tuples
      get(key, default)Returns the value for a key, or a default if not found
      pop(key)Removes the key and returns its value
      popitem()Removes and returns the last added pair
      clear()Removes all items from the dictionary
      fromkeys(seq, v)Creates a new dictionary with keys from seq and values set to v

      Dictionary Unpacking

      Just like lists, you can "unpack" or merge dictionaries using the ** operator.

      python
      1defaults = {'theme': 'dark', 'notifications': True} 2user_settings = {'notifications': False} 3 4# Merge dictionaries (user_settings overwrites defaults) 5final_settings = {**defaults, **user_settings} 6print(final_settings) # {'theme': 'dark', 'notifications': False}

      Conclusion

      Dictionaries are a powerhouse of Python programming. Whether you're handling JSON data or building complex mapping logic, mastering the dict object is a non-negotiable skill for any developer.

      In our next batch of tutorials, we'll look at Sets and Conditional Statements!

      Practice Task

      Create a dictionary representing a simple inventory of 3 items (name and quantity). Then, use the `pop()` method to remove one item.