首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >zyDE 9.15.1:嵌套字典示例:音乐库

zyDE 9.15.1:嵌套字典示例:音乐库
EN

Stack Overflow用户
提问于 2022-02-26 16:26:52
回答 1查看 530关注 0票数 1

所以,我想为那些不能回答这个问题的人回答这个问题。我想帮忙,所以这是我的答案,因为这对我来说有点困难。如果你能想到更好的事情,让大家知道。

zyDE 9.15.1:嵌套字典示例:音乐库。

下面的示例演示使用3级嵌套字典创建简单音乐库的程序。

下面的程序使用嵌套字典来存储一个小型音乐库。扩展程序,以便用户可以将艺术家、专辑和歌曲添加到库中。首先,添加一个命令,将艺术家的名字添加到音乐字典中。然后添加添加专辑和歌曲的命令。在添加专辑之前,要检查词典中是否存在艺术家,在添加歌曲之前,要检查专辑是否存在。

答案:

代码语言:javascript
复制
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: ')
        if artist in music.keys():
            print('That artist already exists. Please try again.')
            artist = input('Artist: ')
        album = input('Album: ')
        for albums in music.values():
            if album in albums:
                print('That album already exists. Please try again')
                album = input('Album: ')
        songs = input('Song: ').split()
        music[artist] = {album: {'songs': songs}}
    else:
        break
    
print(music)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-26 17:04:26

也许你可以试试这个方法:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71278367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档