Home > Software engineering >  dict comprehension with multiple output
dict comprehension with multiple output

Time:09-21

I'd like to fill two dicts simultaneously, like in this example:

def square(num):
    return(num*num,num num)
    
square_dict={}
sum_dict={}
for i in range(1,11):
    square_dict[i],sum_dict[i]=square(i)


print(square_dict)
print(sum_dict)

and I'm wondering if it would be possible to do it with dict comprehension. Something like:

square_dict, sum_dict= [dict(zip(num, square(num)) for num in range(1, 11))]

(which is obviousely not working)

Thanks in advance!

CodePudding user response:

You can zip the key-value pairs from the output of square for each item in range(1, 11) so that you can map the two resulting sequences to the dict constructor:

square_dict, sum_dict = map(dict, (zip(*([(i, v) for v in square(i)] for i in range(1, 11)))))

Demo: https://replit.com/@blhsing/AdventurousDeficientMathematics

Another approach is to zip the output of square into two sequences of squares and sums, and then zip range(1, 11) with each sequence into key-value pairs for dict construction:

square_dict, sum_dict = (dict(zip(range(1, 11), p)) for p in zip(*map(square, range(1, 11))))

Demo: https://replit.com/@blhsing/KindSafeMethods

  • Related