Python - 获取嵌套字典中的密钥

时间:2016-10-28 03:01:51

标签: python dictionary

我知道如何索引和检索以下dict中的几乎所有项目:

playlists={'user':[
               {'playlist':{
                    'tracks': [        
                    {'name': 'Karma Police','artist': 'Radiohead', 'count': "1.0"},
                    {'name': 'Bitter Sweet Symphony','artist': 'The Verve','count': "2.0"}                    
                     ]
                   }
                }
              ]
            }

除外:如何使用string 'playlist'关系打印key/value

2 个答案:

答案 0 :(得分:2)

这确实看起来像一棵复杂的树。可能最好将它包装在一个类中。但无论如何:

例如,获取播放列表中第一首曲目的名称:

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")

这是一个使构建更大的库更容易的例子。获取信息更容易,更快捷,并且比庞大的字典更容易维护!

答案 1 :(得分:0)

您也可以使用iteritems方法简单地访问key/value对,如下所示。而不是像下面那样打印,你可以执行你的行动。

In [14]: user1 = playlists.get('user')[0]

In [15]: for key, value in user1.iteritems():
   ....:     print key
   ....:     print value
   ....:     
playlist
{'tracks': [{'count': '1.0', 'name': 'Karma Police', 'artist': 'Radiohead'}, {'count': '2.0', 'name': 'Bitter Sweet Symphony', 'artist': 'The Verve'}]}