Return Dictionary from a Function in Python
Last Updated :
16 Dec, 2024
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)
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.
Similar Reads
How to Add Function in Python Dictionary Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
4 min read
Returning a function from a function - Python In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior.Example:Pythondef fun1(name): def fun2(): return f"Hello, {name}!" return fun2 # Get the
5 min read
How to return a json object from a Python function? Returning a JSON object from a Python function involves converting Python data (like dictionaries or lists) into a JSON-formatted string or response, depending on the use case. For example, if you're working with APIs, you might return a JSON response using frameworks like Flask. Let's explore sever
2 min read
Use return value in another function - python In Python, one functionâs return value can be used in another, making code cleaner and more modular. This approach simplifies tasks, improves code reuse, and enhances readability. By breaking down logic into smaller functions that share data, you create flexible and maintainable programs. Letâs expl
2 min read
How to call a function in Python Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "de
5 min read