Home > Back-end >  Can a nested loop be compressed into a single line comprehension?
Can a nested loop be compressed into a single line comprehension?

Time:09-29

I have a dictionary containing arrays of integers inside, I would like to be able to traverse all the arrays inside to get the maximum stored value. I have achieved all this with a double nested for loop as shown in the following code snippet:

my_dict = {
    'Key_1': [1, 42, 35],
    'Key_2': [12, 24],
    'Key_3': [80, 8, 58],
}
max_value=0
for values in my_dict.values():
    for v in values:
        if v > max_value:
            max_value = v
print(f'Max value is: {max_value}')

My doubt is if it could be compressed into a single line as shown in this non-functional code snippet:

max_value = (((v if v > max_value else 0) for v in values) for values in my_dict.values())
print(f'Max value is: {max_value}')

Thank you very much in advance.

Regards.

CodePudding user response:

Yes, you can just do:

max(max(x) for x in my_dict.values())

CodePudding user response:

General flow - collection_c = [ (a,b) for a in collection_a for b in collection_b]

CodePudding user response:

Oneliner without Python for loop:

max(max(my_dict.values(), key = max))

Result: 80

The key function i.e. key = max handles the case where the max is not the first item in each list.

  • Related