【发布时间】:2019-01-14 16:06:05
【问题描述】:
我有一个 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
【问题讨论】:
-
你能展示你的尝试吗?似乎是迭代列表并将内部字典一次添加到单个字典的简单案例。
-
您收到错误的原因(在我看来)是您尝试使用数组(列表)中的键访问元素,这是不可能的,请尝试执行 my_link = link[4 ] 然后 my_link["5"] (数组从 0 开始!!)
-
如果您的列表仅包含一项,请使用
channels_json = json.loads(url)[0]。 -
每次我尝试通过引用数组中的值(如下所示)从列表中获取值时,我都会得到
value NameError: name 'value' is not defined
标签: python json string list dictionary