4 回答
TA贡献1951条经验 获得超3个赞
如果您的意思是获取键为元的值,则可以使用next
和理解:
data = ["{'meta':'projects/us/conf/94eb2c1f0574'}","{'del':'projects/us/conf/001a1143e726'}"]
>>> next(v for (k, v) in map(dict.items, data) if k == 'meta') projects/us/conf/94eb2c1f0574
TA贡献1812条经验 获得超5个赞
快速修复是使用 json.loads 将 data[0] 转换为 dict -
value = json.loads(d[0].replace('\'','"'))['meta']
TA贡献1765条经验 获得超5个赞
假设这是数组加载到变量data,data[0]是一键字典'meta'。从那里,您可以通过传递名称来访问该密钥。
>>> data = [{'meta':'projects/us/conf/94eb2c1f0574'}, {'del':'projects/us/conf/001a1143e726'}]
>>> data[0]['meta']
'projects/us/conf/94eb2c1f0574'
TA贡献1810条经验 获得超5个赞
如果您的输入看起来确实像那样(糟糕的 api 设计,或 API 中的错误)
你可以将每个加载为 json
fixed = [json.loads(string_thing.replace("'",'"')) for string_thing in response_array]
>>> fixed[0]['meta']
u'projects/us/conf/94eb2c1f0574'
>>> fixed[1]['del']
u'projects/us/conf/001a1143e726'
如果你想让它成为一个大字典
data = {}
for string_thing in response_array:
# this assumes the strings are valid json and always dicts
data.update(json.loads(string_thing.replace("'",'"')))
>>> data
{u'meta': u'projects/us/conf/94eb2c1f0574', u'del': u'projects/us/conf/001a1143e726'}
>>> data['meta']
u'projects/us/conf/94eb2c1f0574'
>>> data['del']
u'projects/us/conf/001a1143e726'
添加回答
举报