Valen Miriapon Valen Miriapon - 5 months ago 93
Python Question

TypeError: list indices must be integers, not unicode (Telepot retreive name)

I started to learn Python by myself week ago.

I tried to make a bot that retrieve the name of the sender of the chat in a group. I am using Python with 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}]


When I execute this, it gives me this error

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


Error:

TypeError: list indices must be integers, not unicode


How do I fix this?

Answer

Use get() instead of a list to access values in a dictionary. This method returns a value for a given key in a dictionary (or None if the key is not available):

sender1 = response[0][u'message'][u'from'].get(u'first_name')
sender2 = response[0][u'message'][u'from'].get(u'last_name')

# output:
# >>> print sender1
# u'Nick'
# >>> print sender2
# u'Lee'
Comments