data_garden data_garden - 1 month ago 8
Python Question

Python - get key in nested dictionary

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

dict
:

playlists={'user':[
{'playlist':{
'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'
using
key/value
relation?

Answer

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:

print(playlists['user'][0]['playlist']['tracks'][0]['name'])

And the string "Playlist":

print(list(playlists['user'][0].keys())[0])

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=[]):
        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")

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!