문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top