[英]Using a python api that stores a dict in a list of dicts…with no key values
python API(gmusicapi)將播放列表存儲為詞典列表,而曲目信息作為該詞典中的詞典存儲。
-編輯-這是錯誤的。 它在打印時確實具有某種密鑰,但是我無法找到如何在dict中訪問密鑰。
list = [
{ ##this dict isn't a problem, I can loop through the list and access this.
'playlistId': '0xH6NMfw94',
'name': 'my playlist!',
{'trackId': '02985fhao','album': 'pooooop'}, #this dict is a problem because it has no key name. I need it for track info
'owner': 'Bob'
},
{ ##this dict isn't a problem, I can loop through the list and access this.
'playlistId': '2xHfwucnw77',
'name': 'Workout',
'track':{'trackId': '0uiwaf','album': 'ROOOCKKK'}, #this dict would probably work
'owner': 'Bob'
}
]
我試過使用for循環,並通過類似以下方式訪問它:
def playLists(self):
print 'attempting to retrieve playlist song info.'
playListTemp = api.get_all_user_playlist_contents()
for x in range(len(playListTemp)):
tempdictionary = dict(playListTemp[x])
這里的問題是,tempdictionary中有一個稱為track的字典,但是無論我做什么,我似乎都無法訪問其中的鍵/值對。
打印時返回如下內容:
[u'kind', u'name', u'deleted', u'creationTimestamp', u'lastModifiedTimestamp', u'recentTimestamp', u'shareToken', 'tracks', u'ownerProfilePhotoUrl', u'ownerName', u'accessControlled', u'type', u'id', u'description']
其中“ tracks”是包含藝術家,標題,曲目號等的字典
我也嘗試過類似的方法:
tempdictionary ['tracks'] [x] ['title']沒有運氣。 其他時候,我嘗試創建一個新的dict並將它作為音軌,但是隨后我得到一個錯誤,說它需要一個2的值,並且發現了11等。
我是python的新手,所以如果有人可以幫助我,我將非常感激
它在打印時確實具有某種密鑰,但是我無法找到如何在dict中訪問密鑰。
遍歷該字典:
for key in dct:
print(key)
# or do any number of other things with key
如果您還將查看dict的值,請使用.items()
來保存自己的dict查找:
for key, value in dct.items():
print(key)
print(value)
您可能會考慮使用類來封裝常見特征。 當前,您的每個曲目和播放列表詞典都有很多重復的代碼(即“ track_id =”,“ owner =” Bob“)。使用類可以減少重復,並使您的意思更加明顯和明確。
class AudioTrack(object):
def __init__(self, ID, album=None):
self.id = ID
self.album = album
self.owner = 'Bob'
創建單個AudioTrack對象,如下所示:
your_first_track = AudioTrack('02985fhao', 'pooooop')
或創建如下的AudioTrack對象列表:
your_tracks = [
AudioTrack("0x1", album="Rubber Soul"),
AudioTrack("0x2", album="Kind of Blue"),
...
]
這樣,您可以檢查每個AudioTrack對象:
your_first_track.id #Returns '02985fhao'
或對your_tracks中的所有AudioTrack對象執行以下操作:
#Prints the album of every track in the list of AudioTrack intances
for track in your_tracks:
print track.album
您可以使用以下字典來創建播放列表:
my_playlist = {
id: "0x1",
name: "my playlist",
tracks: [AudioTrack("0x1", album="Rubber Soul"),
AudioTrack("0x2", album="Kind of Blue")]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.