使用一个将字典存储在字典列表中的Python API...没有键值

0 投票
2 回答
1673 浏览
提问于 2025-04-30 07:41

这个Python的API(gmusicapi)把播放列表存储成一个字典的列表,每个字典里面又包含了一个关于曲目的信息的字典。

-补充- 这说法不太对。打印出来的时候确实有某种键,但我找不到怎么访问这个字典里的键。

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里面有一个叫做tracks的字典,但我无论怎么做都无法访问里面的键和值。

打印出来的结果大概是这样的:

[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'],但没有成功。还有时候我试着创建一个新的字典,把tracks字典作为值,但结果却报错,说需要一个值为2的东西,而我得到的却是像11这样的东西。

我刚学Python,所以如果有人能帮我解决这个问题,我会非常感激。

暂无标签

2 个回答

1

你可以考虑使用类来封装一些共同的特征。现在,你的每个曲目和播放列表的字典中有很多重复的代码(比如“track_id=”,“owner=Bob”)。使用类可以减少重复代码,让你的意思更加清晰和明确。

class AudioTrack(object):
    def __init__(self, ID, album=None):
        self.id = ID
        self.album = album
        self.owner = 'Bob'

你可以这样创建一个单独的音频曲目对象:

your_first_track = AudioTrack('02985fhao', 'pooooop')

或者这样创建一个音频曲目对象的列表:

your_tracks = [
    AudioTrack("0x1", album="Rubber Soul"),
    AudioTrack("0x2", album="Kind of Blue"),
    ...
    ]

这样的话,你就可以检查每个音频曲目对象:

your_first_track.id     #Returns '02985fhao'

或者对你所有的音频曲目对象做一些操作:

#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")]
    }
3

打印出来的时候确实有一些键,但我不知道怎么在字典里找到这些键。

可以通过遍历字典来查看:

for key in dct:
    print(key)
    # or do any number of other things with key

如果你还想查看字典里的值,可以使用 .items() 这样可以省去查找字典的步骤:

for key, value in dct.items():
    print(key)
    print(value)

撰写回答