How to write a Python function that works with both dictionaries and lists?

PythonPythonBeginner
Practice Now

Introduction

Python is a powerful programming language that offers a wide range of data structures, including dictionaries and lists. In this tutorial, we will explore how to write a Python function that can work seamlessly with both dictionaries and lists, making your code more versatile and adaptable.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/arguments_return("`Arguments and Return Values`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") subgraph Lab Skills python/lists -.-> lab-398284{{"`How to write a Python function that works with both dictionaries and lists?`"}} python/dictionaries -.-> lab-398284{{"`How to write a Python function that works with both dictionaries and lists?`"}} python/arguments_return -.-> lab-398284{{"`How to write a Python function that works with both dictionaries and lists?`"}} python/lambda_functions -.-> lab-398284{{"`How to write a Python function that works with both dictionaries and lists?`"}} end

Python Data Structures Overview

In Python, the two most commonly used data structures are dictionaries and lists. Understanding the differences and use cases of these data structures is essential for writing efficient and versatile Python code.

Dictionaries

Dictionaries are unordered collections of key-value pairs. They are used to store and retrieve data efficiently, with the keys acting as unique identifiers. Dictionaries are often used when you need to associate a piece of data with a specific label or identifier.

Example:

person = {
    "name": "John Doe",
    "age": 35,
    "occupation": "Software Engineer"
}

Lists

Lists are ordered collections of items. They are used to store and manipulate sequences of data, such as numbers, strings, or even other data structures. Lists are useful when you need to work with a collection of related items.

Example:

fruits = ["apple", "banana", "cherry"]

Understanding the strengths and use cases of dictionaries and lists is crucial for writing effective Python functions that can handle a variety of data structures.

Creating a Versatile Function

To create a versatile Python function that can work with both dictionaries and lists, we can use the concept of duck typing. Duck typing is a programming style that focuses on an object's capabilities rather than its type.

The handle_data() Function

Here's an example of a versatile function called handle_data() that can work with both dictionaries and lists:

def handle_data(data):
    if isinstance(data, dict):
        for key, value in data.items():
            print(f"Key: {key}, Value: {value}")
    elif isinstance(data, list):
        for item in data:
            print(item)
    else:
        print("Input must be a dictionary or a list.")

The handle_data() function checks the type of the input data using the isinstance() function. If the input is a dictionary, it iterates through the key-value pairs and prints them. If the input is a list, it iterates through the list items and prints them. If the input is neither a dictionary nor a list, it prints an error message.

Using the handle_data() Function

You can use the handle_data() function with both dictionaries and lists:

## Using the function with a dictionary
person = {
    "name": "John Doe",
    "age": 35,
    "occupation": "Software Engineer"
}
handle_data(person)

## Using the function with a list
fruits = ["apple", "banana", "cherry"]
handle_data(fruits)

## Using the function with an unsupported input
handle_data(42)

This approach allows you to write a single function that can handle different data structures, making your code more flexible and reusable.

Applying the Function to Dictionaries and Lists

Now that we have created the versatile handle_data() function, let's see how we can apply it to both dictionaries and lists.

Applying the Function to a Dictionary

Suppose we have a dictionary representing a person's information:

person = {
    "name": "John Doe",
    "age": 35,
    "occupation": "Software Engineer"
}

We can pass this dictionary to the handle_data() function, and it will print the key-value pairs:

handle_data(person)

Output:

Key: name, Value: John Doe
Key: age, Value: 35
Key: occupation, Value: Software Engineer

Applying the Function to a List

Now, let's apply the handle_data() function to a list of fruits:

fruits = ["apple", "banana", "cherry"]
handle_data(fruits)

Output:

apple
banana
cherry

Handling Unsupported Input

If you pass an input that is neither a dictionary nor a list, the handle_data() function will print an error message:

handle_data(42)

Output:

Input must be a dictionary or a list.

By using the handle_data() function, you can write code that is more flexible and can work with different data structures, making your Python programs more versatile and maintainable.

Summary

By the end of this tutorial, you will have learned how to create a Python function that can handle both dictionaries and lists, allowing you to write more efficient and flexible code. This knowledge will empower you to tackle a variety of programming tasks and expand your Python skills.

Other Python Tutorials you may like