【问题标题】:`TypeError: string indices must be integers` [duplicate]`TypeError:字符串索引必须是整数`[重复]
【发布时间】:2015-08-31 18:48:13
【问题描述】:

我正在尝试在存储库中列出拉取请求的标题和编号。我想将 JSON 作为 dict 返回并打印拉取请求的标题和编号。

如果我只打印标题或编号,我会得到预期的输出,但如果将这些值组合起来打印,我会得到TypeError: string indices must be integers

#!/usr/bin/env python
import github3
from github3 import login, GitHub
import requests
import json
import sys

auth = dict(username="xxxxxxxxx",token="xxxxxxxxx")
gh = login(**auth)

result = gh.repository(owner="xxx", repository="xxxx").pull_request(x)
data  = result.as_dict()
print data['title']['number']

【问题讨论】:

  • 我不熟悉这个 API,但我建议 data['title'] 是一个字符串,而不是你想象的字典。因此,您正在做类似'hello'['number'] 的事情,我希望您同意这是没有意义的。

标签: python python-2.7 github3.py


【解决方案1】:

的确,二位炼金术士所说的都是真的。给定这个例子:

>>> auth = dict(username='larsks', token='mytoken')
>>> gh = login(**auth)
>>> result = gh.repository(owner='ansible', repository='ansible').pull_request(12165)
>>> data = result.as_dict()

我们可以看到data['title']是一个字符串:

>>> data['title']
'Be systematic about parsing and validating hostnames and addresses (proof of concept)'

如果我们想要PR号码,我们可以要求:

>>> data['number']
12165

【讨论】:

  • 阅读错误消息可以学到惊人的东西。 :)
  • Iarsks 和两位炼金术士....感谢您的解释和示例。看了下逻辑就明白了。我试图将一行合并为两行...print data['title']['number']。当我把它分成两个打印语句....print data['title'] 和另一个print data['number'] 的打印语句时,输出是预期的
猜你喜欢
  • 2018-09-16
  • 1970-01-01
  • 2019-03-14
  • 2021-03-28
  • 2021-04-28
  • 2020-06-24
  • 2016-03-26
  • 2017-09-07
相关资源
最近更新 更多