I want my function to return multiple dictionaries based on calling arguments. e.g. if i call the function with no argument, it should return all the dictionaries else if i call it with a list of arguments, it should return the corresponding dictionaries from the function. Apparently if i call with no args or one arg, it works fine but i am having problem with using it with multiple values. Following example shows this problem.
def mydef(arg1=None):
a = {'a1':1, 'a2':2}
b = {'b1':1, 'b2':2}
c = {'c1':1, 'c2':2}
d = {'d1':1, 'd2':2}
if arg1 is None:
return a,b,c,d
else:
for x in arg1:
if x == 'a':
return a
elif x == 'b':
return b
w,x,y,z = mydef()
print type(w)
print w
s,t = mydef(['a', 'b'])
print type(s)
print s
print type(t)
print t
Doubt: Lists are returned instead of dicts:
def mydef(args=None):
dicts = { 'a' :{'a1' : 1, 'a2' :2}, 'b' : {'b1' : 1, 'b2' :2}}
if args is None:
args = ['a', 'b']
return [dicts[d] for d in args]
x,y = mydef()
type(x)
>> type 'dict'
type(y)
>> type 'dict'
x = mydef(['a'])
type(x)
>> type 'list'
A function only gets to return once. You can’t loop and try to return something on each iteration of the loop; the first one returns and that ends the function. If you want to “return multiple values”, what you really have to do is return one value that contains them all, like a list of the values, or a tuple of the values.
Also, it’d be better to put your dictionaries in a dictionary (sup dawg) instead of using local variables to name them. Then you can just pick them out by key.
Here’s a way of doing it that returns a list of the selected dicts: