那麼這個確定看起來像一棵複雜的樹。可能會更好地包裝在一個班級。但不管:
爲了獲得例如在播放列表中的第一首曲目的名稱:
print(playlists['user'][0]['playlist']['tracks'][0]['name'])
和字符串 「播放列表」:
print(list(playlists['user'][0].keys())[0])
它得到令人費解的你需要關鍵和價值,而這並不完全是事情的本意,因爲通常你想提取知道關鍵的價值。我會編輯它,並且稍微更優雅一些,以便在不太長的時間內做到這一點。
好的,假設你有一些python類的經驗,這裏是一個例子。如果沒有,你可以在其他地方找到大量的信息:
# 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")
下面是一個例子,這使得它更容易一些,以建立一個更大的庫。獲取信息更容易,更快捷,而且比維基詞典更容易維護!