Olivia
Olivia

Reputation: 13

How to convert one line code to for in loops?

I'm new to python so this might be a too basic question, but how to I convert these into nested for in loops respectively? - I'm stuck because of the curly brackets.

[{a['artist'] for a in n['tracks']} for user in users for n in user['playlists']]

{v['party'] for vp in vps for v in vp['positions']}

Upvotes: 1

Views: 82

Answers (2)

Alain T.
Alain T.

Reputation: 42143

As a general rule, the first part of the comprehension is the content that would be added/appended to the resulting list/set. The rest is nested loops in the same order as you would have written them using regular for-loop statements.

The first comprehension is building a list of sets. It is a set comprehension nested inside a list comprehension:

result = list()                       # output of comprehension
for user in users:                    # for user in users ...
    for n in user['playlists']:       # for n in user['playlists'] ...
        tracks = set()                    # nested set comprehension {...}
        for a in n['tracks']:             # for a in n['tracks'] ... 
            tracks.add(a['artist'])       # a['artist']
        result.append(tracks)         # list of the tracks sets

The second one is building a set:

result = set()                  # result of comprehension
for vp in vps:                  # for vp in vps ...
    for v in vp['positions']:   # for v in vp['positions'] ...
       result.add(v['party'])   # v['party']

Upvotes: 0

hrmello
hrmello

Reputation: 192

With time this will become more intuitive, but you just need to "unroll" these loops inside those lists. The first one would be:

artists = []
for user in users:
    for n in user["playlists"]:
        for a in n["tracks"]:
            artists.append(a["artist"])     

And the second one:

parties = []
for vp in vps:
    for v in vp["positions"]:
       parties.append(v["party"])

Note that the lists where you'll store the lowest level of the loop, namely "parties" and "artists", should be created before the loop starts.

Upvotes: 1

Related Questions