Python 如何搜索以列表为值的词典?
这是我的家庭作业问题,这个问题给了我一本字典,让我在字典里搜索。这是字典:Python 如何搜索以列表为值的词典?,python,list,dictionary,Python,List,Dictionary,这是我的家庭作业问题,这个问题给了我一本字典,让我在字典里搜索。这是字典: {"childrens": [ ["Be Our Guest", "Angela Lansbury", 224, 0], ["Lullabye", "Billy Joel", 213, 0]], "dance": [ ["Happy Now", "Kygo", 211, 0], ["Grapevine", "Tiesto", 150, 0], ["Headspace", "Dee
{"childrens": [
["Be Our Guest", "Angela Lansbury", 224, 0],
["Lullabye", "Billy Joel", 213, 0]],
"dance": [
["Happy Now", "Kygo", 211, 0],
["Grapevine", "Tiesto", 150, 0],
["Headspace", "Dee Montero", 271, 0]],
"blues": [
["Dream of Nothing", "Bob Margolin", 208, 0]
["Rock and Stick", "Boz Scaggs", 290, 0],
["At Last", "Etta James", 181, 0],
["You’re Driving Me Crazy", "Van Morrison", 286, 0]],
"kpop": [
["Not That Type", "gugudan", 191, 0],
["IDOL", "BTS", 222, 0],
["Believe Me", "Seo In Young", 191, 0],
["Baam", "MOMOLAND", 208, 0],
["Hide Out", "Sultan of the Disco", 257, 0]]
}
关键是“儿童”、“舞蹈”、“布鲁斯”和“kpop”。但问题是,值列表包含多个元素。有整数类型和字符串类型。值列表中的第一项是歌曲的名称,第二项是艺术家的名称。因此,我被要求在字典中搜索这位艺术家并返回歌曲。下面是我的代码
def getSongsByArtist(library, artist):
value = []
value = library.values()
result = []
for sublist in value:
for item in sublist:
if item == artist:
result.append(sublist[0])
return result
我的输出应该是“终于”,但由于某种原因,我的输出是“无梦”,我不明白为什么 您可以尝试使用这一行:
def getSongsByArtist(library, artist):
return [s[0] for l in library.values() for s in l if s[1] == artist]
或以另一种形式:
def getSongsByArtist(library, artist):
# Set up return list
rv = []
# Loop over lists of lists in dictionary values
for l in library.values():
# For each sublist:
for s in l:
# if the artist is correct
if s[1] == artist:
# append the track to the return list
rv.append(s[0])
return rv
用法:
>>> getSongsByArtist(library, 'Billy Joel')
['Lullabye']
您可以尝试使用此一行:
def getSongsByArtist(library, artist):
return [s[0] for l in library.values() for s in l if s[1] == artist]
或以另一种形式:
def getSongsByArtist(library, artist):
# Set up return list
rv = []
# Loop over lists of lists in dictionary values
for l in library.values():
# For each sublist:
for s in l:
# if the artist is correct
if s[1] == artist:
# append the track to the return list
rv.append(s[0])
return rv
用法:
>>> getSongsByArtist(library, 'Billy Joel')
['Lullabye']
试试这个
result = []
for sublist in library:
for item in library[sublist]:
if item[1] == artist:
result.append(item[0])
print(result)
子列表将为您提供所有字典键。使用它可以获取item变量中的值 试试这个
result = []
for sublist in library:
for item in library[sublist]:
if item[1] == artist:
result.append(item[0])
print(result)
子列表将为您提供所有字典键。使用它可以获取item变量中的值 您可以使用更清晰的名称,例如库中的流派。键():
库中的歌曲信息[流派]:
如果歌曲信息[1]==艺术家:
。我试图运行该程序,但遇到一个类型错误:“int”对象没有属性“getitem”。您可以使用更清晰的名称,例如库中的流派。键():对于库中的song_info[流派]:
如果song_info[1]==艺术家:
。我尝试运行该程序,但遇到一个类型错误:“int”对象没有属性“getitem”我尝试运行两个表单,但两个表单都有类型错误:“int”对象没有属性“getitem”>>您向函数传递了什么?我假设library
将是您的字典,而artist
是一个字符串。我尝试运行这两种形式,但都有TypeError:“int”对象没有属性“getitem”>>您向函数传递了什么?我假设library
会像你的问题一样是你的字典,artist
是一个字符串。