crookedleaf
crookedleaf

Reputation: 2198

Simplifying a nested for loop with comprehension

I'm trying to simplify a nested for loop through a dictionary to build a list of unique values (the room sizes that are lists in the nested dictionary values). I have gotten the code reduced down to 4 lines, but was curious if it can be reduced to 1 line through list comprehension in any way.

This is an example python dictionary:

otas = {
    Orbitz: {
        u'Las Vegas': [u'1 Bedroom Suite B-side']
    },
    Expedia: {
        u'Los Angeles': [u'2 Bedroom Lockoff', u'1 Bedroom Deluxe (A-side)', u'3 Bedroom Deluxe']
    },
    Priceline: {
        u'New York': [u'1 Bedroom Deluxe (A-side)']
    },
    Travelocity: {
        u'Chicago': [u'1 Bedroom Deluxe (A-side)', u'2 Bedroom Lockoff']
    }
}

And this is the four lines of code:

rooms = []
for resort in otas.values():
    for room in resort.values():
        rooms += [r for r in room if r not in rooms]

I know there is nothing wrong with the way i'm currently doing it. I'm mostly curious if it can be done.

Upvotes: 1

Views: 912

Answers (3)

avinash pandey
avinash pandey

Reputation: 1381

You can try this

rooms = list(set(reduce(lambda x, y: x+y, [item for x in otas.values() for item in x.values()])))

Upvotes: 1

Kelvin17
Kelvin17

Reputation: 69

If what you want is the rooms with no repetition in the otas dictionary then:

rooms = set([r for resort in otas.values() for room in resort.values() for r in room])

Upvotes: 1

senshin
senshin

Reputation: 10360

I guess you could use a triply-"nested" set comprehension.

rooms = {roomtype
         for service  in otas
         for location in otas[service]
         for roomtype in otas[service][location]}

If you want a list back, just wrap that in a call to list.

Upvotes: 2

Related Questions