【问题标题】:How to find a value for a specific key in python如何在python中查找特定键的值
【发布时间】:2014-01-28 23:17:07
【问题描述】:
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 循环应该与曲目标题变量匹配,但我不知道为什么它不起作用。有没有一种简单的方法来查找已知键的所有值?在这种情况下,键是“名称”

【问题讨论】:

    标签: python for-loop dictionary key-value


    【解决方案1】:

    您必须在tracks 字典中搜索曲目标题。因此,只需像这样更改您的代码

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

    它会打印出来

    match found
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多