简体   繁体   中英

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.

{
  "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? 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:

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"] .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM