Home > Mobile >  zyDE 9.15.1: Nested dictionaries example: Music library
zyDE 9.15.1: Nested dictionaries example: Music library

Time:02-27

So, I wanted to answer this question for those who could not answer this question. I wanted to help, so here is my answer since it was a little hard for me. If you can think of anything better, let everyone know.

zyDE 9.15.1: Nested dictionaries example: Music library.

The following example demonstrates a program that uses 3 levels of nested dictionaries to create a simple music library.

The following program uses nested dictionaries to store a small music library. Extend the program such that a user can add artists, albums, and songs to the library. First, add a command that adds an artist name to the music dictionary. Then add commands for adding albums and songs. Take care to check that an artist exists in the dictionary before adding an album, and that an album exists before adding a song.

Answer:

music = {
    'Pink Floyd': {
        'The Dark Side of the Moon': {
            'songs': [ 'Speak to Me', 'Breathe', 'On the Run', 'Money'],
            'year': 1973,
            'platinum': True
        },
        'The Wall': {
            'songs': [ 'Another Brick in the Wall', 'Mother', 'Hey you'],
            'year': 1979,
            'platinum': True
        }
    },
    'Justin Bieber': {
        'My World':{
            'songs': ['One Time', 'Bigger', 'Love Me'],
            'year': 2010,
            'platinum': True
        }
    }
}

prompt = ("1. Enter artist information\n"
          "2. Exit\n")
command = ''
while command != '2':
    command = input(prompt).lower()
    if command == '1':
        artist = input('Artist: ')
        album = input('Album: ')
        songs = input('Song: ').split()
        music[artist] = {album: {'songs': songs}}
print('\n', music)

CodePudding user response:

Maybe you can try this way:

prompt = ("1. Enter artist information\n"
           "2. Exit\n")
command = ''
while command != '2':
     command = input(prompt).lower()
     if command == '1':
         artist = input('Artist: ')
         album = input('Album: ')
         songs = input('Song: ').split()

        
         if artist in music.keys():
           print(music[artist].keys())
           if album in music[artist].keys():
             music[artist][album]["songs"]  = songs
           else:
             music[artist].update({album: {}})
             music[artist][album].update({"songs": songs})
         else:
           music.update({artist: {}})
           music[artist].update({album: {}})
           music[artist][album].update({"songs": songs})

print('\n', music)
  • Related