【问题标题】:TypeError: string indices must be integers, not str , when trying to create a dictionary类型错误:尝试创建字典时,字符串索引必须是整数,而不是 str
【发布时间】:2015-06-15 17:02:38
【问题描述】:

我正在与一个 INfoblox api 接口,

这是数据的样子..

[
{
    "_ref": "network/ZG5zLm5ldHdvcmskMTAuMTAwLjIyOC4wLzI0LzA:10.100.228.0/24/default", 
    "comment": "jacksonville - mgmt", 
    "network": "10.100.228.0/24", 
    "network_view": "default"
}, 
{
    "_ref": "network/ZG5zLm5ldHdvcmskMTAuMTAwLjIxLjAvMjQvMA:10.100.21.0/24/default", 
    "comment": "miami - mgmt", 
    "network": "10.100.21.0/24", 
    "network_view": "default"
}]

这是我的代码

def foo():
    r = session.get(url + 'network', params={'_max_results': str(5000)})
    z = r.json()
    return dict((h['comment'], h['network']) for h in r.content)
    #return r.content

我在执行上述函数时收到错误“TypeError:字符串索引必须是整数,而不是 str”。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    你可能想使用z:

    return dict((h['comment'], h['network']) for h in z)
    

    【讨论】:

    • 现在我得到一个 KeyError: 'comment' ,可以用上面的字典吗?还是每个网络都应该是一本字典?
    • @wwi:那你的数据不是你发布的。
    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多