Loops 如何将某些内容删除并在词典中打印出来?
我正在做一个家庭作业,我不知道如何从字典中删除一首歌曲,如何获得只打印歌曲列表中的艺术家的功能Loops 如何将某些内容删除并在词典中打印出来?,loops,python-3.x,dictionary,Loops,Python 3.x,Dictionary,我正在做一个家庭作业,我不知道如何从字典中删除一首歌曲,如何获得只打印歌曲列表中的艺术家的功能 pl=[] song ={"song":"Baby","artist":"Justin Bieber","duration":220,"genre":"pop"} pl.append(song) def printPlaylist(pl): for i in range (0,len(pl)): play = pl [i]
pl=[]
song ={"song":"Baby","artist":"Justin Bieber","duration":220,"genre":"pop"}
pl.append(song)
def printPlaylist(pl):
for i in range (0,len(pl)):
play = pl [i]
print("song-",play["song"])
print("artist-",play["artist"])
print("duration-",play["duration"])
print("genre-",play["genre"])
print("---")
print("raw list")
printPlaylist(pl)
def addSong(pl,song,artist,duration,genre="pop"):
pl.append ({"song":title,"artist":singer,"duration":time,"genre":kind})
def removeSongs(pl,song):
title = ("Enter a song")
if song in pl:
del song[title]
else:
print = ("Song not in list")
def listByArtist(pl):
listByArtist = sorted(listByArtist,key=pl
要获取字典的特定值,请按其键调用它:
song ={"song":"Baby","artist":"Justin Bieber","duration":220,"genre":"pop"}
artist = song["artist"]
print artist #Justin Bieber
从字典中删除是什么意思?要从列表中删除歌曲而不是从字典中删除歌曲,您需要如下smth:
def removeSongs(pl, song):
removed_indices = []
for ix, s in enumerate(pl):
if s["song"] == song:
removed_indices.append(ix)
for i in removed_indices:
del pl[i]
return True if removed_indices else False
title = raw_input("Enter song title to remove: ")
smth_was_removed = removeSongs(playlist, title)
if not smth_was_removed:
print("No such song")
else:
print("All songs with that title were removed")
>>> x = {"a": 1, "b": 2, "c": 3}
>>> del x["b"]
>>> x
{"a": 1, "c": 3}
然后你可以这样使用它:
def removeSongs(pl, song):
removed_indices = []
for ix, s in enumerate(pl):
if s["song"] == song:
removed_indices.append(ix)
for i in removed_indices:
del pl[i]
return True if removed_indices else False
title = raw_input("Enter song title to remove: ")
smth_was_removed = removeSongs(playlist, title)
if not smth_was_removed:
print("No such song")
else:
print("All songs with that title were removed")
>>> x = {"a": 1, "b": 2, "c": 3}
>>> del x["b"]
>>> x
{"a": 1, "c": 3}
此外,del不应该像列表上那样使用;如果要从列表中删除项目,需要知道其索引:
>>> a = ["Erik", "John", "Mary"]
>>> del a[1] # deletes "John"
>>> a
["Erik", "Mary"]
在字典上,它的工作原理如下:
def removeSongs(pl, song):
removed_indices = []
for ix, s in enumerate(pl):
if s["song"] == song:
removed_indices.append(ix)
for i in removed_indices:
del pl[i]
return True if removed_indices else False
title = raw_input("Enter song title to remove: ")
smth_was_removed = removeSongs(playlist, title)
if not smth_was_removed:
print("No such song")
else:
print("All songs with that title were removed")
>>> x = {"a": 1, "b": 2, "c": 3}
>>> del x["b"]
>>> x
{"a": 1, "c": 3}
如何从字典中删除歌曲。谢谢你帮我。你的意思是从字典中删除歌曲:宝贝吗?这正是它要求从播放列表中删除歌曲的目的。您将删除在歌曲中传递了子字符串的所有歌曲。因此,如果用户使用“by”调用函数,例如,它将删除歌曲“Baby”。打印一条消息,指示用户是否成功删除了歌曲,或者歌曲是否不在播放列表中。