简体   繁体   English

如何搜索以列表为值的字典?

[英]How to search through a dictionary with lists as values?

This is my homework question, the question gives me a dictionary and ask me to search through the dictionary.这是我的作业题,题目给了我一本字典,让我去查字典。 This is the 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 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]]
}

the keys are "childrens", "dance", "blues", and "kpop".键是“children”、“dance”、“blues”和“kpop”。 But the thing is that the value list contains more than one elements.但问题是值列表包含多个元素。 There are both integer and string types.有整数和字符串类型。 The first item in the value list is the name of song, the second one is the name of the artist.值列表中的第一项是歌曲名称,第二项是艺术家姓名。 So I am asked to search the artist through the dictionary and return the song.所以我被要求通过字典搜索艺术家并返回歌曲。 Below is my code.下面是我的代码。

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

I should get "At Last" for the output, but for some reason my output is "Dream of Nothing", I can't figure out why.我的输出应该是“At Last”,但由于某种原因,我的输出是“Dream of Nothing”,我不明白为什么。

You can try using this one-liner:您可以尝试使用这个单线:

def getSongsByArtist(library, artist):
    return [s[0] for l in library.values() for s in l if s[1] == artist]

or in another form:或以另一种形式:

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

Usage:用法:

>>> getSongsByArtist(library, 'Billy Joel')
['Lullabye']

Try this试试这个

result = []
for sublist in library:
    for item in library[sublist]:
        if item[1] == artist:
           result.append(item[0])        
print(result)

sublist will give you all dictionary keys. sublist 会给你所有的字典键。 Using that get the values in the item variable.使用它获取项目变量中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM