python - 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
解决方案
dd = {}
for d in c:
for key, value in d.items():
dd[key] = value
推荐阅读
- angular - 防止以角度 6 下载 config.ts 文件
- netbeans - 在 Apache Netbeans 9.0 中更改主题
- google-cloud-platform - 使用 terraform 创建 google_sql_user 始终会重新创建资源
- swift - Swift4 - 意外发现 nil - 将图像设置为按钮
- php - PHP / 连接到 Sphinx 需要用户名 / 密码
- c# - 如何为 List 类型实体编写 Razor 代码?
- ios - iOS - 视图(ViewController),具有持久数据
- php - 无法从 PHP 创建视图,但可以从 phpMyAdmin
- c# - 如何使正则表达式正确验证信息?
- adonis.js - adonijs 身份验证失败,出现 401 错误,并使用正确的电子邮件和密码