Open In App

Return Dictionary from a Function in Python

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Returning a dictionary from a function allows us to bundle multiple related data elements and pass them back easily. In this article, we will explore different ways to return dictionaries from functions in Python.

The simplest approach to returning a dictionary from a function is to construct it directly within the function and return it. This is straightforward and easy to understand.

Python
def get():
    d = {'name': 'John', 'age': 21, 'major': 'Computer Science'}
    return d

res = get()
print(res)

Output
{'name': 'John', 'age': 21, 'major': 'Computer Science'}

Explanation:

  • In this example, the function get() constructs a dictionary with student details and returns it.
  • The dictionary contains three key-value pairs: 'name', 'age' and 'major'.
  • When the function is called, the dictionary is returned and printed.

Let's take a look at other cases of returning dictionary from a function in python:

Returning a Dictionary Using a Dictionary Constructor

If the data we are working with is stored as a list of tuples or if we need to dynamically generate key-value pairs, we can use the dict() constructor. This method is particularly useful when we want to create a dictionary from pairs of values.

Python
def get(keys, values):
    return dict(zip(keys, values))

keys = ['name', 'age', 'major']
values = ['Alice', 22, 'Mathematics']

res = get(keys, values)
print(res)

Output
{'name': 'Alice', 'age': 22, 'major': 'Mathematics'}

Explanation:

  • The function get() takes two lists: keys and values and pairs them up using the zip() function.
  • The zip() function combines corresponding elements from the two lists into tuples, which are then passed to the dict() constructor to create a dictionary.
  • The result is a dictionary that maps each key to its corresponding value.

Using Dictionary Comprehension to Return a Dictionary

Another advanced method to return a dictionary is using dictionary comprehension. This allows for more flexibility, as we can apply conditions or transformations to generate the dictionary's contents.

Python
def get(n):
    return {i: i ** 2 for i in range(1, n + 1)}

res = get(5)
print(res)

Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Explanation:

  • In this case, the function get() creates a dictionary where the keys are integers from 1 to n and the values are the squares of those integers.
  • Dictionary comprehension is used to efficiently generate the dictionary in one line.

Returning a Dictionary with Dynamic Keys

We can also return a dictionary with keys that are generated dynamically based on input parameters or other data structures. This method is especially useful when the dictionary keys are not known in advance and are generated during runtime.

Python
def fun(username, email, age):
    d = {}
    d['username'] = username
    d['email'] = email
    d['age'] = age
    return d

res = fun('SHIVANG', '[email protected]', 22)
print(res)

Output
{'username': 'SHIVANG', 'email': '[email protected]', 'age': 22}

Explanation:

  • The fun() function dynamically constructs a dictionary based on the arguments passed to it: username, email and age.
  • The function returns a dictionary with these values, which can be used for user profile data.

Returning Nested Dictionaries

Python also allows us to return dictionaries that contain other dictionaries as values. This is useful when representing hierarchical data structures.

Python
def fun():
    d = {
        'name': 'Laptop',
        'details': {
            'brand': 'Dell',
            'price': 800,
            'ram': '16GB'
        }
    }
    return d

res = fun()
print(res)

Output
{'name': 'Laptop', 'details': {'brand': 'Dell', 'price': 800, 'ram': '16GB'}}

Explanation:

  • The fun() function returns a dictionary where the value of the 'details' key is itself another dictionary containing specific product details.
  • This showcases how you can have nested dictionaries, which are useful for modeling complex data structures.

Next Article
Article Tags :
Practice Tags :

Similar Reads