Sling Academy
Home/Python/Python: How to access and modify dictionary items

Python: How to access and modify dictionary items

Last updated: February 13, 2024

Introduction

Dictionaries in Python are an essential data structure for storing and accessing data. They work like a real-life dictionary, storing information as key-value pairs. This flexible structure enables storing a wide range of data types and structures, from numbers and strings to lists and even other dictionaries. This tutorial provides a comprehensive guide on accessing and modifying dictionary items, packed with basic to advanced examples to help you navigate through Python dictionaries efficiently.

Preparing a Sample Dict

To begin with, let’s understand the basic structure of a dictionary. A dictionary in Python can be created using curly braces {} with key-value pairs separated by colons. For instance:

my_dict = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

Accessing Dictionary Items

Once you have a dictionary, you may want to know how to access its items. Accessing dictionary items can be done by referring to its key name, wrapped in square brackets, or using the get method. Here are examples of both methods:

# Using square brackets
print(my_dict['name'])

# Using the get method
print(my_dict.get('name'))

When using square brackets, if the key does not exist, it will raise a KeyError. The get method, on the other hand, returns None if the key isn’t found, making it a safer option if you’re not sure whether the key exists.

Modifying Dictionary Items

Modifying dictionary items is equally straightforward. You can change the value associated with a specific key simply by assigning a new value to it. Adding new key-value pairs is just a matter of assignment as well. Observe the examples below:

# Modifying an existing key's value
my_dict['age'] = 31

# Adding a new key-value pair
my_dict['profession'] = 'Engineer'

Using the update() Method

Beyond basic access and modification, dictionaries offer several methods and functionalities that make them extremely versatile. For instance, the update method allows you to merge two dictionaries. This can be particularly useful when you need to update multiple items at once or add new items from another dictionary.

# Merging two dictionaries
other_dict = {
    'skill': 'Python',
    'years_of_experience': 5
}
my_dict.update(other_dict)

Advanced Examples

To further explore the capabilities of Python dictionaries, let’s delve into some advanced applications.

Dictionary Comprehension

This advanced feature allows you to create dictionaries using an iterative approach, akin to list comprehensions. For example, to create a dictionary that maps numbers to their squares:

squares = {x: x*x for x in range(6)}

Using Lambda Functions

You can use lambda functions to filter or sort dictionaries. For instance, to sort a dictionary by its values:

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

Nested Dictionaries

Sometimes the values within a dictionary are dictionaries themselves. This is perfect for representing hierarchical data. Accessing items in nested dictionaries requires chaining key references:

nested_dict = {
    'employee1': {
        'name': 'John',
        'age': 30
    },
    'employee2': {
        'name': 'Mary',
        'age': 25
    }
}

# Accessing items in a nested dictionary
print(nested_dict['employee1']['name'])

Summary

In summary, dictionaries in Python are highly powerful and versatile. They enable efficient data organization and retrieval through simple syntax and a rich set of functionalities. Whether you’re a beginner or advancing in Python, mastering dictionaries will significantly enhance your coding capabilities. With the examples and explanations provided in this tutorial, you’re well-prepared to utilize dictionaries in your Python projects. Always remember, the best way to learn is by doing. So, dive into coding, experiment with these examples, and discover the powerful potential of Python dictionaries.

Next Article: How to clone a dictionary in Python – Shallow and Deep Copies

Previous Article: 3 ways to iterate through a dictionary in Python

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types