1

I'm receiving the following error

TypeError: string indices must be integers

when I'm trying to print some data that is within a nested dictionary

{u'id': u'000123', u'payload': u"{'account_title': u’sam b’, 'phone_num': ‘1234567890’, 'security_pin': u'000000', 'remote_word': u’secret123’, 'email_address': ‘email@gmail.com’, 'password': u’password123’}”}

For example, let's say the above was assigned to the variable 'account_info'

print(account_info['payload']) <- will print everything from 'payload' onwards

but when I use:

print(account_info['payload']['email_address'])

I get the error

TypeError: string indices must be integers

Any ideas? Thanks!

bharatk
  • 4,202
  • 5
  • 16
  • 30
srb7
  • 337
  • 2
  • 9

4 Answers4

2

Since payload's value is a string, not a dictionary, it cannot be indexed as such. Remove the quotes around the nested dictionary for the code to work:

account_info = {u'id': u'000123', u'payload': {'account_title': u'sam b', 'phone_num': '1234567890', 'security_pin': u'000000', 'remote_word': u'secret123', 'email_address': 'email@gmail.com', 'password': u'password123'}}

print(account_info["payload"]["email_address"])
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

As payload value is a string, you need to convert it to dict before indexing. There are few ways of doing it, here is one with eval:

import ast
...
payload = ast.literal_eval(account_info['payload'])
print(payload['email_address'])
Andrei
  • 55,890
  • 9
  • 87
  • 108
0

account_info['payload'] is a string with bad single quotes, so you should remove all bad single quotes with the replace method and convert the string into a dictionary using ast.literal_eval(). without removing bad single quotes ast.literal_eval() method will raise SyntaxError: invalid character in identifier error.

Ex.

import ast
account_info = {u'id': u'000123', u'payload': u"{'account_title': u’sam b’, 'phone_num': ‘1234567890’,"
                               u" 'security_pin': u'000000', 'remote_word': u’secret123’, "
                               u"'email_address': ‘email@gmail.com’, 'password': u’password123’}"}

account_info['payload'] = ast.literal_eval(account_info['payload'].replace("‘","'").replace("’","'"))
print(account_info['payload']['email_address'])

O/P:

email@gmail.com
bharatk
  • 4,202
  • 5
  • 16
  • 30
0

The way you defined it the value of account_info['payload'] is a string object that looks like a dictionary. Define it like this instead:

account_info = {u'id': u'000123', u'payload': {u'account_title': u’sam b’, u'phone_num': ‘1234567890’, u'security_pin': u'000000', u'remote_word': u’secret123’, u'email_address': u‘email@gmail.com’, u'password': u’password123’}}

With this definition the value of account_info['payload'] is now a dictionary and account_info['payload']['email_address'] will return 'email@gmail.com'

mathism
  • 63
  • 1
  • 6