简体   繁体   中英

“TypeError: string indices must be integers, not str” when trying to get item from python dictionary

I have such a code in order to fetch some data from a url:

import urllib2
response = urllib2.urlopen('https://api.genderize.io/?name=joseph')
html = response.read()

>>> print html
{"name":"joseph","gender":"male","probability":"0.99","count":923}

Everything up to here is fine. But when I want to fetch "gender" data from this dictionary;

>>> print html["gender"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str

I get the above error.

How can I fix the problem?

That's because html is of type string. To validate that, try:

>>> type(html)
<type 'str'>

Hence the error message saying that string indices must be integers, not str .

You should convert it to JSON using json module:

json.loads(html)['gender']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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