首页 > 解决方案 > json.load 痛苦创建字典而不是列表

问题描述

我有一个 python 脚本,它从 json 中的站点获取数据:

channels_json = json.loads(url)

该站点返回数据如下:

[ { '1': 'http://ht.co/bbda24210d7bgfbbbbcdfc2a023f' },
{ '2': 'http://ht.co/bbd10d7937932965369c248f7ccdfc2a023f' },
{ '3': 'http://ht.co/d3a01f6e5e74eb2cb5840556d80a52adf2871d' },
{ '4': 'http://ht.co/56d3a01f6e5e72cb5840556d80a52adf2871d' },
{ '5': 'http://ht.co/9ed0bb4cc447b99c9ce609916ccf931f16a' },
{ '6': 'http://ht.co/9ed0bb4cc44bb99c9ce609916ccf931f16a' },
....]

问题是 Python 正在将它变成一个列表而不是字典。所以我不能像这样引用'4':

print (channels_json["4"])

并得到回应:

http://ht.co/56d3a01f6e5e72cb5840556d80a52adf2871d    

相反,Python 吐出:

TypeError: list indices must be integers, not str

如果我运行此代码:

for c in channels_json:
   print c

Python 打印出每组耦合数据,如下所示:

{u'1': u'http://ht.co/bbda24210d7bgfbbbbcdfc2a023f' },
{ u'2': u'http://ht.co/bbd10d7937932965369c248f7ccdfc2a023f' },
{ u'3': u'http://ht.co/d3a01f6e5e74eb2cb5840556d80a52adf2871d' },
{ u'4': u'http://ht.co/56d3a01f6e5e72cb5840556d80a52adf2871d' },
{ u'5': u'http://ht.co/9ed0bb4cc447b99c9ce609916ccf931f16a' },
{ u'6': u'http://ht.co/9ed0bb4cc44bb99c9ce609916ccf931f16a' },

如何将上述内容放入字典中,以便可以将值“6”作为字符串引用并返回

http://ht.co/9ed0bb4cc44bb99c9ce609916ccf931f16a

标签: pythonjsonstringlistdictionary

解决方案


 dd = {}

 for d in c:
     for key, value in d.items():
         dd[key] = value

推荐阅读