Python:迭代嵌套字典

时间:2016-10-29 04:58:31

标签: python dictionary iteration

给出以下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"}                    
                     ]
                  }
                },
              ]
            }

虽然不是很优雅,但我可以在这样的结构中获取键和值:

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感到困惑。

我该怎么办?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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']

请注意,这将为播放列表中的所有用户提供播放列表/艺术家的组合列表