以下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
工具。
我該怎麼辦?
您也可以找到''通過名單user'(playlists.keys所有用戶的播放列表/藝術家組合名單())[0]'在Python 3中。 – TheRandomGuy