[英]How to fetch the key and values from response and store it in a json file using python?
I have a python code in this format that wants to fetch the key and values from response.我有一个这种格式的 python 代码,它想要从响应中获取键和值。
def test()
data={u'Application': u'e2e', u'Cost center': u'qwerty', u'Environment': u'E2E', u'e2e3': u'aktest1', u'e2etest': u'aktest2', u'S68e2e': u'function',u'Application': u'test', u'Cost center': u'qwerty', u'Environment': u'E2E', u'e2e3': u'test7nov', u'e2etest': u'testapi', u'S68e2e': u'function'}
new={}
for k,v in data.items():
new["key"] = k
new["tags"] = []
for d in v:
flds = list(d)
new["tags"].append({"key": k, "values": flds})
print(new["tags"])
with open(fileName, 'w') as f:
json.dump(new["tags"], f, indent=3 * ' ')
test()
I am getting output as我得到 output 作为
[ {'key': 'S68e2e', 'values': ['f']},
{'key': 'S68e2e', 'values': ['u']},
{'key': 'S68e2e', 'values': ['n']},
{'key': 'S68e2e', 'values': ['c']},
{'key': 'S68e2e', 'values': ['t']},
{'key': 'S68e2e', 'values': ['i']},
{'key': 'S68e2e', 'values': ['o']},
{'key': 'S68e2e', 'values': ['n']}]
which is not correct.I expected to be这是不正确的。我希望是
[{'key': 'Application', 'values': 'e2e'}{'key': 'Cost center', 'values': 'qwerty'}{'key': 'e2etest', 'values': 'aktest2'}]
You can use a list comprehension to create a list of dictionaries that wrap your key,values in other key values您可以使用列表推导来创建一个字典列表,这些字典将您的键、值包装在其他键值中
[{ 'key': k, 'values': v } for k, v in data.items()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.