[英]How do I format this dictionary in python?
I'm making a chatbot to detect toxicity, using the google perspective API, It responds with a dictionary shown below.我正在制作一个聊天机器人来检测毒性,使用谷歌视角 API,它响应如下所示的字典。
{
"attributeScores": {
"TOXICITY": {
"spanScores": [
{
"begin": 0,
"end": 11,
"score": {
"value": 0.05588363,
"type": "PROBABILITY"
}
}
],
"summaryScore": {
"value": 0.05588363,
"type": "PROBABILITY"
}
}
},
"languages": [
"en"
],
"detectedLanguages": [
"en"
]
}
How can I format the above json to get the first "value": 0.05588363 as either a string or int?如何格式化上述 json 以获得第一个“值”:0.05588363作为字符串或整数? Help would be much appreciated!
帮助将不胜感激!
This is my code:这是我的代码:
from googleapiclient import discovery
import json
import os
API_KEY= os.getenv('API_KEY')
service = discovery.build('commentanalyzer', 'v1alpha1', developerKey=API_KEY)
analyze_request = {
'comment': { 'text': 'sample text' },
'requestedAttributes': {'TOXICITY': {}}
}
response = service.comments().analyze(body=analyze_request).execute()
val = (json.dumps(response, indent=2))
print(val)
final = val["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"]
print(final)
Maybe a more general solution to your problem, instead of using a script with "hardcoded" values & enumerations:对于您的问题,也许是一个更通用的解决方案,而不是使用带有“硬编码”值和枚举的脚本:
It converts all int/float values to strings, however it's easy to modify it to convert only the values of specific keys as well:它将所有 int/float 值转换为字符串,但是很容易修改它以仅转换特定键的值:
def handler(data):
if data is not None:
res = {}
for k,v in data.items():
if type(v) not in (dict, list):
res[k] = str(v) if type(v) in (int, float) else v
elif type(v) == list:
t_list = []
for rec in v:
if type(rec) in (dict, list):
tmp_l = [{k2:v2} for k2, v2 in handler(rec).items()]
t_list.append(tmp_l)
else: t_list.append(rec)
res[k] = t_list[0]
else: res[k] = handler(v)
return res
else: return None
results = handler(data)
print(results)
That would be something along the lines of dict["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"]
.这将类似于
dict["attributeScores"]["TOXICITY"]["spanScores"][0]["score"]["value"]
。
i define your dictionary as a dict:我将您的字典定义为字典:
d = dict({
"attributeScores": {
"TOXICITY": {
"spanScores": [
{
"begin": 0,
"end": 11,
"score": {
"value": 0.05588363,
"type": "PROBABILITY"
}
}
],
"summaryScore": {
"value": 0.05588363,
"type": "PROBABILITY"
}
}
},
"languages": [
"en"
],
"detectedLanguages": [
"en"
]
})
and then access to the value by keys:然后通过键访问值:
d['attributeScores']['TOXICITY']['summaryScore']['value']
>>0.05588363
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.