How to Return a Dictionary in Python?

Estimated read time 1 min read

To return a dictionary in Python, you can simply use the return statement followed by the dictionary object. Here’s an example:

def get_dictionary():
    dictionary = {"key1": "value1", "key2": "value2"}
    return dictionary

# Call the function and assign the returned dictionary to a variable
result = get_dictionary()

# Access the dictionary outside the function
print(result)  # Output: {"key1": "value1", "key2": "value2"}

In this example, the get_dictionary() function creates a dictionary named dictionary and returns it using the return statement. When calling the function and assigning its return value to the result variable, you can access the dictionary outside the function.

The return statement allows you to provide the dictionary object as the result of the function, making it available for further use or assignment outside the function scope.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply