Aligning objects long side along the X axis

I have a bunch of objects rotated 90deg on various axis, what I want for them to do is be layed out neatly longest side along X axis. It should be dead simple but for some reason i need to run the code twice for it to actually work. Halp…

import bpy
from math import pi

for o in bpy.context.visible_objects:
    bpy.context.scene.objects.active = o
    x, y, z = o.dimensions #write XYZ dimensions to variables

    if z>x:
        o.rotation_euler = (0, (pi*90/180), 0)
    if y>x:
        o.rotation_euler = (0, 0, (pi*90/180))

Nvm, I got it right this time

import bpy
from math import pi

for o in bpy.context.visible_objects:
    bpy.context.scene.objects.active = o
    o.select = True
    bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
    x, y, z = o.dimensions#write XYZ dimensions to variables
    while x<z or x<y:
       if z>x:
            o.rotation_euler = (0, (pi*90/180), 0)
            bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
       if y>x:
            o.rotation_euler = (0, 0, (pi*90/180))
            bpy.ops.object.transform_apply(location=True, rotation=True, scale=Tru
       x, y, z = o.dimensions
    if x>y and x>z:
        bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
    o.select = False