简体   繁体   English

Python通过嵌套字典排序

[英]Python Sorting Through Nested Dictionaries

I'm working with the Twitch API and I have a large nested dictionary. 我正在使用Twitch API,我有一个大的嵌套字典。 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? 有谁知道为什么r.text与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 谢谢

print r.text returns the str version of the object, while r.text returns the repr version of the object. print r.text返回对象的str版本,而r.text返回对象的repr版本。

>>> 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 . 你的字典键是字符串,如果你使用r.text[stream]那么python会查找一个名为stream的变量,因为它没有找到它会引发NameError

Simply use : r.text['stream'] 只需使用: 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'}}

First, you are trying to access an element in a string, not a dictionary. 首先,您尝试访问字符串中的元素,而不是字典。 r.text simply returns the plain text of the request. r.text只返回请求的纯文本。 To get the proper dictionary from a requests object, use r.json() . 要从requests对象获取正确的字典, requests使用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 . 当你尝试r.json()[stream] ,Python认为你在字典中寻找与它们位于变量stream键相对应的值。 You have no such variable. 你没有这样的变数。 What you want is the value corresponding to the key of the literal string 'stream'. 你想要的是与文字字符串'stream'的键对应的值。 Therefore, r.json()['stream'] should give you what you the next nested dictionary. 因此, r.json()['stream']应该为您提供下一个嵌套字典。 If you want that url, then r.json()['stream']['_links']['self'] should return it. 如果你想要那个网址,那么r.json()['stream']['_links']['self']应该返回它。

See Ashwini's answer for why print r.text and r.text are different. 请参阅Ashwini的答案,了解为什么print r.textr.text不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM