Question

I'm working with the Twitch API and I have a large nested dictionary. How do I sift through it?

>>> r = requests.get('https://api.twitch.tv/kraken/streams/sibstlp', headers={'Accept': 'application/vnd.twitchtv.v2+json'})

then:

>>> print r.text
#large nested dictionary starting with
#{"stream":{"_links":{"self":"https://api.twitch.tv/kraken/streams/sibstlp"},

interestingly:

>>> r.text
# large nested dictionary starting with
#u'{"stream":{"_links":{"self":"https://api.twitch.tv/kraken/streams/sibstlp"},

Does anyone know why r.text is different from print r.text?

How do I work through the dictionaries to get the information out that I'm looking for? I'm currently trying:

>>> r.text[stream]
NameError: name 'stream' is not defined

Thanks

Was it helpful?

Solution

First, you are trying to access an element in a string, not a dictionary. r.text simply returns the plain text of the request. To get the proper dictionary from a requests object, use r.json().

When you try r.json()[stream], Python thinks that you are looking for the value in the dictionary corresponding to they key located in variable stream. You have no such variable. What you want is the value corresponding to the key of the literal string 'stream'. Therefore, r.json()['stream'] should give you what you the next nested dictionary. If you want that url, then r.json()['stream']['_links']['self'] should return it.

See Ashwini's answer for why print r.text and r.text are different.

OTHER TIPS

print r.text returns the str version of the object, while r.text returns the repr version of the object.

>>> x = 'foo'
>>> print x     #equivalent to : print str(x)
foo
>>> print str(x)
foo
>>> x           #equivalent to  : print repr(x)
'foo'
>>> print repr(x)
'foo'

Your keys of that dictionary are strings, if you use r.text[stream] then python will look for a variable named stream and as it is not found it'll raise NameError.

Simply use : r.text['stream']

Demo:

>>> d= {"stream":{"_links":{"self":"https://api.twitch.tv/kraken/streams/sibstlp"}}}
>>> d['stream']
{'_links': {'self': 'https://api.twitch.tv/kraken/streams/sibstlp'}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top