Search code examples
pythondictionarynestedpython-requeststwitch

Lookup value inside dictionary-of-dictionary


I'm creating a Python application where you input a Twitch emote name, and it spits out a link to the image. (i.e.; If I input "Kappa", the result will be a link to this) I can use an API to get the emote name and id, but the entries in the returned JSON are formatted as such:

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

What I want to get is a dictionary like such:

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

I've tried plenty of methods (parsing as XML, key-value pairs), and nothing has worked. Here's my code so far:

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)

Solution

  • How about just using a dict comprehension to create the dictionary you want:

    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"