从嵌套字典中提取数据,TypeError:字符串索引必须为整数

时间:2019-09-09 12:44:50

标签: python json dictionary

我收到以下错误

TypeError: string indices must be integers

当我尝试打印嵌套字典中的某些数据时

{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’}”}

例如,假设上面已分配给变量“ account_info”

print(account_info['payload']) <-将打印从“有效负载”开始的所有内容

但是当我使用时:

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

我收到错误

TypeError: string indices must be integers

有什么想法吗?谢谢!

4 个答案:

答案 0 :(得分:2)

由于payload的值是一个字符串,而不是字典,因此无法这样索引。删除嵌套字典周围的引号以使代码起作用:

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"])

答案 1 :(得分:0)

由于payload的值是一个字符串,因此需要在索引之前将其转换为dict。有few ways of doing it,这是一个eval:

import ast
...
payload = ast.literal_eval(account_info['payload'])
print(payload['email_address'])

答案 2 :(得分:0)

git help <verb>是带有account_info['payload']的字符串,因此您应该使用replace方法删除所有错误的单引号,然后使用将字符串转换为字典。而不删除错误的单引号bad single quotes方法将引发ast.literal_eval()

例如。

SyntaxError: invalid character in identifier error

O / P:

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'])

答案 3 :(得分:0)

您定义account_info['payload']值的方式是一个看起来像字典的字符串对象。像这样定义它:

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’}}

使用此定义,account_info['payload']的值现在是字典,account_info['payload']['email_address']将返回'email@gmail.com'