所以,我想為那些無法回答這個問題的人回答這個問題。我想幫忙,所以這是我的答案,因為這對我來說有點難。如果您能想到更好的方法,請告訴所有人。
zyDE 9.15.1:嵌套字典示例:音樂庫。
下面的例子演示了一個程式,它使用 3 級嵌套字典來創建一個簡單的音樂庫。
以下程式使用嵌套字典來存盤一個小型音樂庫。擴展程式,以便用戶可以將藝術家、專輯和歌曲添加到庫中。首先,添加一個將藝術家姓名添加到音樂詞典的命令。然后添加用于添加專輯和歌曲的命令。在添加專輯之前,請注意檢查字典中是否存在藝術家,以及在添加歌曲之前是否存在專輯。
回答:
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)
uj5u.com熱心網友回復:
也許您可以嘗試這種方式:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434472.html
上一篇:python無法從字串中獲取字典
下一篇:如何從字典中的字典中獲取最大值?
