How can we return a dictionary from a Python function?


Any object, such as dictionary, can be the return value of a Python function. Create the dictionary object in the function body, assign it to any variable, and return the dictionary to the function's caller.

Data values are stored as key:value pairs in dictionaries. A Python dictionary is a collection that is ordered, changeable, and forbids duplicates.

In this article we will discuss various methods to return a dictionary from a Python function.

Using Dictionary Comprehension

One line of Python code can create and initialise dictionaries using the simple and memory efficient way known as Dictionary Comprehension. Expression and context are the two components of dictionary comprehension. The expression specifies the key-value mapping. The context specifies which (key, value) pairs to include in the new dictionary by iterating over an iterable using a single-line for loop.

Example

The following example shows how to apply a specific expression to obtain the key:value mapping stored for the loop variable "x" while iterating over all elements in a specified context "for x in range(6)". In this instance, it is the key-value mapping 'x:str(x)' that maps an integer 'x' to its string representation 'str(x)'.

def create_dictionary(): # returning the dictionary return {x:str(x) for x in range(6)} counts = create_dictionary() print('The returned dictionary is:',counts)

Output

Following is an output of the above code −

The returned dictionary is: {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5'}

Using Lambda function

A lambda function in Python is an anonymous function. It begins with the keyword lambda, is followed by a list of zero or more arguments separated by commas, the colon, and the return expression. For the purpose of creating and returning a new dictionary object, use the dict() function or the curly braces {}.

Example

In the following example, the lambda function assigns a function object created dynamically to the 'create_dictionary' variable. After that, you can call the function as done in the previous example.

It is impossible to be more concise than the generator expression, which creates a dictionary and returns it simultaneously in a single line of code.

create_dictionary = lambda : {x:str(x) for x in range(6)} counts = create_dictionary() print('The returned dictionary is:',counts)

Output

Following is an output of the above code −

The returned dictionary is: {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5'}

By returning the dictionary using return statement

To send the function's result back to the caller, you can use the Python return statement inside of a function or method. The return keyword is followed by an optional return value in a return statement. Any Python object may be the return value of a Python function.

Example

In the following example we created a function ‘create_dictionary’ which is used to create a dictionary by assigning values to keys. Once the dictionary is created we returned it using the return statement.

def create_dictionary(): d = dict(); d['Sachin Tendulkar'] = "Cricket" d['Wayne Gretzky'] = "Hockey" d['Cristiano Ronaldo'] = "Football" d['Novak Djokovic'] = "Tennis" return d print ('The returned dictionary is:',create_dictionary())

Output

Following is an output of the above code −

The returned dictionary is: {'Sachin Tendulkar': 'Cricket', 'Wayne Gretzky':
'Hockey', 'Cristiano Ronaldo': 'Football', 'Novak Djokovic': 'Tennis'}

Updated on: 27-Aug-2023

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements