data_garden data_garden - 10 months ago 107
Python Question

Python - get key in nested dictionary

I know how to index and retrieve almost every item in the following


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

except: how do I print the
string 'playlist'

Answer Source

Well this sure seems like a complicated tree. Might be better to wrap it in a class. But regardless:

To get for example the name of the first track in the playlist:


And the string "Playlist":


It gets convoluted as you need both the key and the value, and this is not exactly how things necessarily were meant to be, since usually you wish to extract the value knowing the key. I'll edit this and whip up a slightly more elegant way to do this in not too long.

Okay, so assuming you have some experience with classes in python, here is an example. If not, you can find plenty of information on that elsewhere:

# Class based example

class Playlist(object):
    def __init__(self, name, tracks=[]): = name
        self.tracks = tracks

    def GetTrack(self, searchString):
        for T in self.tracks:
            if searchString in
                return T
            return  None

    def AddTrack(self, track):
        if isinstance(track, Track):
            pass # Or do some exception handling

class Track(object):
    def __init__(self, name, artist, count): = 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

# And exception handle it
SongToGet = AnotherPlaylist.GetTrack("Sasdjkl")

if not SongToGet:
    print ("Could not find song")

Here is an example which makes it a little easier to build a larger library. It is easier and quicker to get information, and is also easier to maintain than a huge dictionary!