given the following dictionary
:
playlists={'user':[
{'playlist1':{
'tracks': [
{'name': 'Karma Police','artist': 'Radiohead', 'count': "1.0"},
{'name': 'Bitter Sweet Symphony','artist': 'The Verve','count': "2.0"}
]
}
},
{'playlist2':{
'tracks': [
{'name': 'We Will Rock You','artist': 'Queen', 'count': "3.0"},
{'name': 'Roxanne','artist': 'Police','count': "5.0"}
]
}
},
]
}
though not very elegantly, I can fetch keys and values in such a structure:
keys
:
userX = [user[0] for user in playlists.iteritems()][0] //userX
playlist1 = list(playlists['userX'][0].keys())[0] //playlist1
and nested values
:
artist = playlists['user'][0]["playlist1"]['tracks'][0]['artist'] //Radiohead
count = playlists['user'][1]["playlist2"]['tracks'][0]['count'] //3.0
but I'm a bit confused as to how access all playlists names for playlists
and all artists for tracks in playlists
using any iteration
tool.
how can I do it?
You can use following code to access the playlist names and artist names:
# Define generator to return dicts under each user
lists = (x for user in playlists.itervalues() for x in user)
print [name for play_list in lists for name in play_list.iterkeys()]
lists = (x for user in playlists.itervalues() for x in user)
track_lists = (content['tracks'] for p in lists for content in p.itervalues())
print [track['artist'] for track_list in track_lists for track in track_list]
Output:
['playlist1', 'playlist2']
['Radiohead', 'The Verve', 'Queen', 'Police']
Note that above works only with Python 2, with Python 3 values
& keys
should be used instead of itervalues
& iterkeys
.
If you are looking to extract a flat list of all playlist names you can use a list comprehension. The mix of dictionaries and lists adds a little complexity.
all_playlists = [ playlist_title
for user in playlists
for user_playlists in playlists[user]
for playlist_title in user_playlists ]
print all_playlists
all_artists = [ track['artist']
for user in playlists
for user_playlists in playlists[user]
for playlist_title in user_playlists
for track in user_playlists[playlist_title]['tracks'] ]
print all_artists
gives
['playlist1', 'playlist2']
['Radiohead', 'The Verve', 'Queen', 'Police']
Note that this will give combined lists of playlists/artists across all users in the playlists dict
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.