[英]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.