简体   繁体   中英

What is the most pythonic way to create a 'For Loop' that filters through a dictionary?

I am looking to search for and then append an item through a dictionary (named: songs) that contains a list of tracks. However, this dictionary has multiple levels and indices. Here is my code:

artists = []

for i in range(len(songs['tracks'])):
     artist.append(songs['tracks'][i]['artists'][0]['name'])

Is there a more pythonic way of writing this code? I feel as though using in range(len(songs['tracks'])) is not the best way to achieve this, but it does the job.

一个等同于您的代码的解决方案可能是

artists = [track['artists'][0]['name'] for track in songs['tracks']]

First of all, what you're doing there is actually a "map" operation (transforming the items of one array into another array/list), not a "filter" operation (removing certain items that match a condition from an array/list).

Second, you shouldn't be looping over a range. This is a for in loop, not a traditional for loop, so there's no index. Instead, each iteration contains the item in the list/array.

artists = []
for track in songs['tracks']:
    artists.append(track['artists'][0]['name'])

You can turn this into a one liner using list comprehensions . They take the common premise of iterating over a list to create a new list, possibly transforming the results and possibly filtering the results. The syntax they use is:

result = [ <transformation> for item in items if <condition> ]

In your case you don't have an explicit need for a condition since you're simply mapping one set of array values to another, like this:

artists = [ track[artists][0]['name'] for track in songs['tracks'] ]

However, if you were filtering, that if condition would be what you'd use. For example

artists_with_long_songs = [ track[artists][0]['name'] for track in songs['tracks'] if track['length'] > 600 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM