Question

I am getting a type error for this piece of code.

dataTable = {a :1, "data":{b:2, "children":[{c:3, "data":{d:4,e:5, "likes": null, f:6.....} } } }
data = dataTable["data"]["children"]["data"]["likes"]

Output:

TypeError: string induces must be integers, not str

Could anyone work out the problem in my code and explain why? Thanks!

Était-ce utile?

La solution

This is because dataTable["data"]["children"] is not a dictionary, it is a list:

>>> dataTable = {'a' :1, "data":{'b':2, "children":[{'c':3, "data":{'d':4,'e':5, "likes": 'null', 'f':6} }] } }
>>> type(dataTable["data"]["children"])
<type 'list'>

If you want a specific item from the list, get it by index:

>>> dataTable["data"]["children"][0]['data']['likes']
'null'

If you want all children, iterate over the list:

>>> for child in dataTable["data"]["children"]:
...     print child['data']['likes']
... 
null

Autres conseils

dataTable["data"]["children"] is a list, so it makes no sense to query data on it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top