<p>这棵树看起来很复杂。最好在类中包装它。但不管怎样:</p>
<p>例如,要获取播放列表中第一首曲目的名称:</p>
<p><code>print(playlists['user'][0]['playlist']['tracks'][0]['name'])</code></p>
<p>以及字符串“Playlist”:</p>
<p><code>print(list(playlists['user'][0].keys())[0])</code></p>
<p>它变得复杂起来,因为您需要键和值,而这并不完全是事物的本来面目,因为通常您希望在知道键的情况下提取值。我会编辑这篇文章,然后在不久的时间内想出一个稍微优雅一点的方法。在</p>
<p>好的,假设您对python中的类有一定的经验,下面是一个示例。如果没有,你可以在其他地方找到大量的信息:</p>
<pre><code># Class based example
class Playlist(object):
def __init__(self, name, tracks=[]):
self.name = name
self.tracks = tracks
def GetTrack(self, searchString):
for T in self.tracks:
if searchString in T.name:
return T
else:
return None
def AddTrack(self, track):
if isinstance(track, Track):
self.tracks.append(Track)
else:
pass # Or do some exception handling
class Track(object):
def __init__(self, name, artist, count):
self.name = name
self.artist = artist
self.count = count
def Play(self):
pass # Could in theory add some play functionality
# Now you would create a new playlist by going:
MyPlaylist = Playlist("Heavy Metal")
MyPlaylist.AddTrack("SomeSong", "SomeArtist", 1) # etc
# Or
Countrysongs = [Track("SongName", "ArtistName", 12), Track("Bobby", "The Artist", 2)]
AnotherPlaylist = Playlist("Country", Countrysongs)
# And to access the Playlist name or the Song Name
MyPlaylist.GetTrack("SongName")
# And exception handle it
SongToGet = AnotherPlaylist.GetTrack("Sasdjkl")
if not SongToGet:
print ("Could not find song")
</code></pre>
<p>下面是一个例子,它使构建一个更大的库变得更容易一些。它比一本大字典更容易、更快地获取信息,也更容易维护!在</p>