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”. 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.
2
Answers
You can try using this one-liner:
or in another form:
Usage:
Try this
sublist will give you all dictionary keys. Using that get the values in the item variable.