2016-10-29 113 views
0

以下dictionary的Python:迭代給定的嵌套字典

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"}      
        ] 
        } 
       }, 
       ] 
      } 

雖然不是很優雅,我可以在這樣的結構中提取的鍵和值:

keys

userX = [user[0] for user in playlists.iteritems()][0] //userX 
playlist1 = list(playlists['userX'][0].keys())[0] //playlist1 

和嵌套values

artist = playlists['user'][0]["playlist1"]['tracks'][0]['artist'] //Radiohead 
count = playlists['user'][1]["playlist2"]['tracks'][0]['count'] //3.0 

但我有點困惑如何訪問所有playlists names for playlists和所有artists for tracks in playlists使用任何iteration工具。

我該怎麼辦?

+0

您也可以找到''通過名單user'(playlists.keys所有用戶的播放列表/藝術家組合名單())[0]'在Python 3中。 – TheRandomGuy

回答

0

您可以使用下面的代碼來訪問播放列表的名稱和藝術家名稱:

# 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] 

輸出:

['playlist1', 'playlist2'] 
['Radiohead', 'The Verve', 'Queen', 'Police'] 

注意,上面的Python 2只工作,與Python 3 values & keys應代替itervalues & iterkeys

0

如果您想要提取所有播放列表名稱的平面列表,您可以使用列表理解。字典和列表的混合增加了一點複雜性。

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 

['playlist1', 'playlist2'] 
['Radiohead', 'The Verve', 'Queen', 'Police'] 

注意,這將會給整個的播放列表字典