[英]Python Can't access dictionary
Getting TypeError: string indices must be integers
when trying to access a dictionary in python.获取类型错误
TypeError: string indices must be integers
尝试在 python 中访问字典时, TypeError: string indices must be integers
。 I've tried using json.loads(r2)
thos produces "TypeError: the JSON object must be str, bytes or bytearray, not dict"
我试过使用
json.loads(r2)
thos 产生"TypeError: the JSON object must be str, bytes or bytearray, not dict"
Not even sure if Im on the right track here, all I need to do is get the JSON which appears to be in one long string into something like x['SomeKey']
and the value at those keys using iteritems()
or similar?甚至不确定我在这里是否在正确的轨道上,我需要做的就是使用
iteritems()
或类似方法将似乎在一个长字符串中的 JSON 转换为类似x['SomeKey']
和这些键的值?
r = requests.get(url, headers=headers)
r2 = r.json()
seq = json.dumps(r2)
print(seq['remotecontrol_id'])
r.json()
already returns a dictionary so I'm not sure why you pass r2
to json.dumps
that returns a string (hence the s
). r.json()
已经返回了一个字典,所以我不知道你为什么将r2
传递给返回一个字符串的json.dumps
(因此是s
)。 The error message you received even suggests that ("TypeError: the JSON object must be str, bytes or bytearray, not dict ")您收到的错误消息甚至表明 ("TypeError: the JSON object must be str, bytes or bytearray, not dict ")
Your code should be你的代码应该是
r = requests.get(url, headers=headers)
r2 = r.json()
print(r2['remotecontrol_id'])
The problem is that method dumps
converts a python's dictionary
into a string
, therefore in the line seq['remote...']
you are accessing a string
.问题是方法
dumps
将 python 的dictionary
转换为string
,因此在seq['remote...']
您正在访问string
。 You should access the variable r2
instead of seq
您应该访问变量
r2
而不是seq
Ok, I got it figured out, sort of...好吧,我明白了,有点……
for i in r2:对于 r2 中的 i:
print(r2['stuff'][0]['someval1']) print(r2['stuff'][1]['asomeval2'])打印(r2['stuff'][0]['someval1'])打印(r2['stuff'][1]['asomeval2'])
Anyway, hits works无论如何,点击有效
Thanks for all the great advice!感谢所有伟大的建议!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.