Skip to main content
 首页 » 编程设计

python之如何在 python 中查找特定键的值

2024年11月01日7飞鱼

import requests 
import json 
 
# initial message 
message = "if i can\'t let it go out of my mind" 
 
# split into list 
split_message = message.split() 
 
def decrementList(words): 
    for w in [words] + [words[:-x] for x in range(1,len(words))]: 
        url = 'http://ws.spotify.com/search/1/track.json?q=' 
        request = requests.get(url + "%20".join(w)) 
 
        json_dict = json.loads(request.content) 
        num_results = json_dict['info']['num_results'] 
        if num_results > 0: 
            num_removed = len(words) - len(w) 
 
            #track_title = ' '.join(words) 
 
            track_title = "If I Can't Take It with Me" 
 
            for value in json_dict.items(): 
                if value == track_title: 
                    print "match found" 
 
            return num_removed, json_dict 
 
 
num_words_removed, json_dict = decrementList(split_message) 

在下面的代码中,我尝试将歌曲名称与我的搜索查询相匹配。在这个特定的查询中,歌曲不会匹配,但我添加了一个变量来匹配返回查询的歌曲。函数末尾的 for 循环应该与轨道标题变量相匹配,但我不明白为什么它不起作用。有没有一种简单的方法可以找到已知 key 的所有值?在这种情况下,键是“名称”

请您参考如下方法:

您必须在 tracks 字典中搜索轨道标题。所以,只需像这样更改您的代码

for value in json_dict["tracks"]: 
    if value["name"] == track_title: 

它会打印

match found