字典中的字典中的查找值

Lookup value inside dictionary-of-dictionary

我正在创建一个 Python 应用程序,您可以在其中输入 Twitch 表情名称,它会向图像输出 link。 (即;如果我输入 "Kappa",结果将是 link 到 this)我可以使用 API 来获取表情名称和 ID,但是条目返回的 JSON 格式如下:

"id":{"code": "emote name","channel":"channel name", "set":"set number"}

我想要得到的是这样的字典:

{"emote name": "id", "emote name": "id"...}

我尝试了很多方法(解析为 XML,键值对),但没有任何效果。到目前为止,这是我的代码:

import requests

r = requests.get("http://twitchemotes.com/api_cache/v2/images.json")
# Here, I'd handle the JSON from the response; however I don't know how.
query_name = input("Enter emote name:")
for k,v in emote_dict.items()
  if k == query_name:
    response = "http://static-cdn.jtvnw.net/emoticons/v1/" + v + "/1.0"
print("Here you go: " + response)

对于 Python 2.7 或 3.0 及更高版本:

如果您JSON喜欢

response = {"id": {"code": "emote name", "channel": "channel name", "set": "set number"},  ... }

像这样用 dict comprehension 试试:

{val["code"]: id_ for id_, val in response.items()}

它将响应的 JSON 重新映射为新的形式

{emote name: id, emote name: id, ...}

使用 dict comprehension 创建您想要的词典如何:

emote_dict ={value.get('code'):emote_id for (emote_id, value) in r.json()['images'].iteritems()}
query_name = raw_input("Enter emote name:").strip()
if query_name in emote_dict:
    response = "http://static-cdn.jtvnw.net/emoticons/v1/" + emote_dict[query_name] + "/1.0"

假设您已经将 images.json 下载到您的本地文件系统(即它不会经常更改):

import json

with open('/path/to/images.json') as f_in:
    orig_json = json.loads(f_in.read())

emote_dict = {value['code']: key for key, value in orig_json['images'].items()}

因为响应的 JSON 数据看起来像这样:

{
    "images": {
        "11540": {
            "code": "getvexxedGetvexxed",
            "set": 3483,
            "channel": "vexxgaming"
        },
        "11541": {
            "code": "makMak",
            "set": 3515,
            "channel": "morninafterkill"
          .
          .
          .
        "38346": {
            "code": "cynicalWeasel",
            "set": 634,
            "channel": "totalbiscuit"
        }
    },
    "meta": {
        "generated_at": "2015-08-25T02:30:11Z"
    }
}

您可以创建 emote_dict 字典,就像您说的那样,使用 dictionary comprehension 表达式,例如最后一行:

import requests

response = requests.get("http://twitchemotes.com/api_cache/v2/images.json")
emote_dict = {v["code"]: k for k, v in response.json()["images"].items()}

并像这样使用它:

query_name = input("Enter emote name:")
id = emote_dict.get(query_name)
if not id:
    print('{} emote name not found'.format(query_name))
else:
    image_link= "http://static-cdn.jtvnw.net/emoticons/v1/" + id + "/1.0"
    print("Here you go: " + image_link)