Python 字符串索引必须是整数-Django

Python 字符串索引必须是整数-Django,python,django,dictionary,Python,Django,Dictionary,我有一本相当大的字典,看起来像这样: { 'startIndex': 1, 'username': 'myemail@gmail.com', 'items': [{ 'id': '67022006', 'name': 'Adopt-a-Hydrant', 'kind': 'analytics#accountSummary', 'webProperties': [{ 'id': 'UA-67522226-1', 'name': 'Ad

我有一本相当大的字典,看起来像这样:

{
'startIndex': 1,
'username': 'myemail@gmail.com',
'items': [{
    'id': '67022006',
    'name': 'Adopt-a-Hydrant',
    'kind': 'analytics#accountSummary',
    'webProperties': [{
        'id': 'UA-67522226-1',
        'name': 'Adopt-a-Hydrant',
        'websiteUrl': 'https://www.udemy.com/,
        'internalWebPropertyId': '104343473',
        'profiles': [{
            'id': '108333146',
            'name': 'Adopt a Hydrant (Udemy)',
            'type': 'WEB',
            'kind': 'analytics#profileSummary'
        }, {
            'id': '132099908',
            'name': 'Unfiltered view',
            'type': 'WEB',
            'kind': 'analytics#profileSummary'
        }],
        'level': 'STANDARD',
        'kind': 'analytics#webPropertySummary'
    }]
}, {
    'id': '44222959',
    'name': 'A223n',
    'kind': 'analytics#accountSummary', 

And so on....
当我把这本字典复制到我的Jupyter笔记本上,我在django代码上运行与预期完全相同的函数,一切都是一样的,在django代码中,我甚至打印了字典,然后我把它复制到笔记本上,运行它,我得到了我期望的结果

欲了解更多信息,请参阅以下功能:

google_profile = gp.google_profile # Get google_profile from DB
print(google_profile)
all_properties = []
for properties in google_profile['items']:
    all_properties.append(properties)

site_selection=[]
for single_property in all_properties:
    single_propery_name=single_property['name']
    for single_view in single_property['webProperties'][0]['profiles']:
        single_view_id = single_view['id']
        single_view_name = (single_view['name'])
        selections = single_propery_name + ' (View: '+single_view_name+' ID: '+single_view_id+')'
        site_selection.append(selections)
print (site_selection)
我猜我的笔记本上安装了某种json解析器之类的东西?可能吗?为什么在django,我不能像在ipython笔记本上那样访问字典

编辑

更多信息: 错误出现在以下行:
对于google_profile['items']中的属性:
Django调试是:
TypeError at/gconnect/string索引必须是整数

本地变量是:

all_properties =[]
current_user = 'myemail@gmail.com'
google_profile  = `the above dictionary`

因此,为了让谁能发现这个问题,我想说清楚:

如果将词典保存在数据库中,django会将其保存为字符串,因此在保存后您将无法访问它

要解决此问题,可以将其重新转换为字典:

我的答案对我来说非常有效,换句话说:

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}
将字符串转换为字典的方法有很多,这只是其中之一。如果您遇到此问题,您可以快速检查它是否是字符串而不是字典,并使用:

print(type(var))
就我而言,我有:

在用上述方法转换之前,我得到


一切都按预期运行

在函数中哪里发生了错误?你能显示实际的错误消息吗?嘿@ScottHunter我添加了更多信息,thanksgoogle_profile是一个字符串,因此你不能使用['items',这只适用于dicts、defaultdicts和OrderedDicts或实现GetItems的类,这是正确的,json解决了以下问题:
导入json
s=”{'muffin':'lolz','foo':'kitty'}“
json\u acceptable\u string=s.replace(“'”,“\”)
d=json.loads(json\u acceptable\u string)
d={u'muffin':u'lolz',u'foo':u'kitty'}