python - 如何搜索以列表为值的字典?
问题描述
这是我的作业题,题目给了我一本字典,让我在字典里搜索。这是字典:
{"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']
推荐阅读
- pycharm - 如何防止这种情况:我将焦点切换到不同的应用程序(alt+tab),切换回 Pycharm,然后项目树崩溃?
- paypal - 客户贝宝按钮购买后更改谷歌驱动器链接
- php - 为什么有些电子邮件 ID 被接受而有些不是 PHP
- python - 使用返回看不到结果
- android - 字段重叠,以编程方式创建布局
- ruby-on-rails - 通过层次结构获取平均总和
- java - 如何在 JavaDoc 中链接 com.android.Volley 包
- c++ - STL 的头文件
- powershell - 如何在powershell中拆分大于X的文本文件行?
- excel - VBA查找和替换到不同的列,同一行,SKIP IF Cell有一个值