简体   繁体   中英

how can i take a specific element from this list in python?

I'm working with the Microsoft Azure face API and I want to get only the glasses response. heres my code:

########### Python 3.6 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json

###############################################
#### Update or verify the following values. ###
###############################################

# Replace the subscription_key string value with your valid subscription key.
subscription_key = '(MY SUBSCRIPTION KEY)'

# Replace or verify the region.
#
# You must use the same region in your REST API call as you used to obtain your subscription keys.
# For example, if you obtained your subscription keys from the westus region, replace 
# "westcentralus" in the URI below with "westus".
#
# NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
# a free trial subscription key, you should not need to change this region.
uri_base = 'https://westcentralus.api.cognitive.microsoft.com'

# Request headers.
headers = {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': subscription_key,
}

# Request parameters.
params = {
    'returnFaceAttributes': 'glasses',
}

# Body. The URL of a JPEG image to analyze.
body = {'url': 'https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg'}

try:
    # Execute the REST API call and get the response.
    response = requests.request('POST', uri_base + '/face/v1.0/detect', json=body, data=None, headers= headers, params=params)

    print ('Response:')
    parsed = json.loads(response.text)
    info = (json.dumps(parsed, sort_keys=True, indent=2))
    print(info)

except Exception as e:
    print('Error:')
    print(e)

and it returns a list like this:

[
  {
    "faceAttributes": {
      "glasses": "NoGlasses"
    },
    "faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6",
    "faceRectangle": {
      "height": 162,
      "left": 177,
      "top": 131,
      "width": 162
    }
  }
]

I want just the glasses attribute so it would just return either "Glasses" or "NoGlasses" Thanks for any help in advance!

I think you're printing the whole response, when really you want to drill down and get elements inside it. Try this:

print(info[0]["faceAttributes"]["glasses"])

I'm not sure how the API works so I don't know what your specified params are actually doing, but this should work on this end.

EDIT: Thank you to @Nuageux for noting that this is indeed an array, and you will have to specify that the first object is the one you want.

I guess that you can get few elements in that list, so you could do this:

info = [
  {
    "faceAttributes": {
      "glasses": "NoGlasses"
    },
    "faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6",
    "faceRectangle": {
      "height": 162,
      "left": 177,
      "top": 131,
      "width": 162
    }
  }
]

for item in info:
    print (item["faceAttributes"]["glasses"])

>>> 'NoGlasses'

你试过了吗:
glasses = parsed[0]['faceAttributes']['glasses']

This looks more like a dictionary than a list. Dictionaries are defined using the { key: value } syntax, and can be referenced by the value for their key. In your code, you have faceAttributes as a key that for value contains another dictionary with a key glasses leading to the last value that you want.

Your info object is a list with one element: a dictionary. So in order to get at the values in that dictionary, you'll need to tell the list where the dictionary is (at the head of the list, so info[0]).

So your reference syntax will be:

#If you want to store it in a variable, like glass_var
glass_var = info[0]["faceAttributes"]["glasses"] 
#Or if you want to print it directly
print(info[0]["faceAttributes"]["glasses"])

What's going on here? info[0] is the dictionary containing several keys, including faceAttributes , faceId and faceRectangle . faceRectangle and faceAttributes are both dictionaries in themselves with more keys, which you can reference to get their values.

Your printed tree there is showing all the keys and values of your dictionary, so you can reference any part of your dictionary using the right keys:

print(info["faceId"]) #prints "0f0a985e-8998-4c01-93b6-8ef4bb565cf6"
print(info["faceRectangle"]["left"]) #prints 177
print(info["faceRectangle"]["width"]) #prints 162

If you have multiple entries in your info list, then you'll have multiple dictionaries, and you can get all the outputs as so:

for entry in info: #Note: "entry" is just a variable name, 
                   #  this can be any name you want. Every 
                   #  iteration of entry is one of the 
                   #  dictionaries in info.
    print(entry["faceAttributes"]["glasses"])

Edit: I didn't see that info was a list of a dictionary, adapted for that fact.

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