Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python return with multiple dictionaries from a function

my problem is that I have two function and one of it's return value is two dictionaries in the following way:

def fnct1():
    return dict1, dict2

so it's returning into my other function which return value is the two dictionaries from the previous function and also a new dictionary, so something like this

 def fnct2():
     return dict3, fnct(1)

the problem with this is that is has the following result:

({dict3},({dict1},{dict2})

but I want it to look the following way:

({dict3},{dict1},{dict2})
like image 514
Kiftau Avatar asked Jul 10 '26 06:07

Kiftau


2 Answers

Since your function returns a tuple, you need to either return the individual tuple items, or unpack them:

def fnct1():
    dict1 = { "name": "d1" }
    dict2 = { "name": "d2" }
    return dict1, dict2

def fnct2():
    dict3 = { "name": "d3" }
    res = fnct1() 
    return dict3, res[0], res[1] # return the individual tuple elements

# alternative implementation of fnct2:
def fnct2():
    dict3 = { "name": "d3" }
    d1, d2 = fnct1() # unpack your tuple
    return dict3, d1, d2

print(fnct2())
# Output: ({'name': 'd3'}, {'name': 'd1'}, {'name': 'd2'})
like image 149
Mike Scotty Avatar answered Jul 13 '26 15:07

Mike Scotty


You could unpack the values from fnct1() before returning them:

def fnct2():
    dict1, dict2 = fnct1()
    return dict3, dict1, dict2
like image 43
kyriakosSt Avatar answered Jul 13 '26 15:07

kyriakosSt