python - 类型错误:列表索引必须是整数,而不是 unicode(Telepot 检索名称)

标签 python typeerror

我试图制作一个机器人来检索群组中聊天发件人的姓名。我将 Python 与 Telepot 结合使用。

>>> from pprint import pprint
>>> import telepot
>>> response = bot.getUpdates()
pprint(response)
[{u'message': {u'chat': {u'first_name': u'Nick',
                         u'id': 999999999,
                         u'last_name': u'Lee',
                         u'type': u'private'},
           u'date': 1444723969,
           u'from': {u'first_name': u'Nick',
                     u'id': 999999999,
                     u'last_name': u'Lee'},
           u'message_id': 4015,
           u'text': u'Hello'},
u'update_id': 100000000}]

当我执行这个时,它给我这个错误

sender1 = response[u'message'][u'from'][u'first_name']
sender2 = response[u'message'][u'from'][u'last_name']

错误:

TypeError: list indices must be integers, not unicode

我该如何解决这个问题?

最佳答案

表示中的方括号表示您有一个列表,列表必须使用整数或切片进行索引。在尝试访问任何包含的词典之前,尝试通过 [0] 建立索引。

关于python - 类型错误:列表索引必须是整数,而不是 unicode(Telepot 检索名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771482/

相关文章:

python - 尝试在 python 中创建一个 virtualenv 并激活它

python - 以特定方式合并单位矩阵

python - 为什么从 Python 2 移植到 Python 3 时 ord() 会失败?

python:在函数内表现不佳的dict-错误的TypeError

javascript - 为什么我不能 var a = someFn.call; A();?

python - 在 Python Tkinter 中创建模态对话框是否需要 wait_window()?

python - 如何使用 Python pip 安装 google.cloud?

Python:打开具有定义的驱动器盘符的文件 - TypeError:需要整数

python - 这个错误: "TypeError: Parameters to generic types must be types"?是什么意思

python - 使用 scikit-learn 的 SGDRegressor 算法进行梯度下降