Python Return Dictionary From Function

5/5 - (2 votes)

Do you need to create a function that returns a dictionary but you don’t know how? No worries, in sixty seconds, you’ll know! Go! ?

A Python function can return any object such as a dictionary. To return a dictionary, first create the dict object within the function body, assign it to a variable your_dict, and return it to the caller of the function using the keyword operation “return your_dict“.

Basic Method to Create and Return Dict from Function

For example, the following code creates a function create_dict() that adds all numbers 0, 1, 2, …, 9 as dictionary keys to your_dict and the respective string representations as dictionary values, and returns the dict to the caller of the function:

def create_dict():
    ''' Function to return dict '''
    your_dict = {}
    for i in range(10):
        your_dict[i] = str(i)
    return your_dict

numbers = create_dict()
# {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5',
#  6: '6', 7: '7', 8: '8', 9: '9'}

Attention: Variable Scope!

Note that you store the resulting dictionary in the variable numbers. The local variable your_dict that you created within the function body is only visible within the function but not outside of it. So, if you try to access the name your_dict, Python will raise a NameError:

>>> print(your_dict)
Traceback (most recent call last):
  File "", line 9, in <module>
NameError: name 'your_dict' is not defined

To fix this, simply assign the return value of the function — a dictionary — to a new variable and access the content of this new variable:

>>> numbers = create_dict()
>>> print(numbers)
{0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}

Return Dict From Function Using Dictionary Comprehension

There are many other ways to return a dictionary from a function in Python. For example, you can use a dictionary comprehension statement instead that is much more concise than the previous code—but creates the same dictionary of number mappings:

def create_dict():
    ''' Function to return dict '''
    return {i:str(i) for i in range(10)}

numbers = create_dict()
# {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}

With dictionary comprehension, you can dynamically create a dictionary by using the syntax {expression context}. You iterate over all elements in a given context “for i in range(10)“, and apply a certain expression to obtain the key:value mapping stored for the loop variable i. In our case, that’s the key:value mapping i:str(i) that maps an integer i to its string representation str(i).

In case you need to learn more about dictionary comprehension, feel free to check out this explainer video from Finxter:

Python Dictionary Comprehension - A Powerful One-Liner Tutorial

Related Article: A Simple Introduction to Dictionary Comprehension in Python

Return Dictionary From Function Using Lambda

An interesting way to return a dict from a function is to use lambda functions.

A lambda function is an anonymous function in Python. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. Use the dict() constructor or the curly braces { ... } to create and return a new dict object.

The following code snippet uses a combination of features.

  • The lambda function dynamically creates a function object and assigns it to the variable create_dict. You can then call the function like before with create_dict().
  • The generator expression creates a dictionary and returns it at the same time in a single line of code—it cannot get more concise than that.
create_dict = lambda : {i:str(i) for i in range(10)}

numbers = create_dict()
# {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!

Programmer Humor

“Real programmers set the universal constants at the start such that the universe evolves to contain the disk with the data they want.”xkcd