[英]json.load agony to create dictionary instead of list
我有一个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
您可以通过遍历从json.load()
返回的list
的字典来创建所需的字典,如下所示:
#json_data = json.loads(url)
json_data = [{ '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' },]
# Convert to single dictionary.
channels_json = dict(d.popitem() for d in json_data)
print(json.dumps(channels_json, indent=4)) # Pretty-print result.
输出:
{
"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"
}
dd = {}
for d in c:
for key, value in d.items():
dd[key] = value
您可以遍历数组并构建字典
channels_json = {}
channels_array = json.loads(url)
for d in channels_array:
key = list(d.keys())[0]
val = d[key]
channels_json[key] = val
现在,您应该能够引用您的字典channels_json
这样做的更多pythonic方法。
channels = {}
for i in json.loads(url): channels.update(i)
要么
channels = {}
[channels.update(i) for i in json.loads(url)]
在这两种情况下,词典都会使用您的单独词典列表进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.