Home > Software design >  Find a value in a list of dictionaries
Find a value in a list of dictionaries

Time:09-24

I have the following list:

 {

   "id":1,
   "name":"John",
   "status":2,
   "custom_attributes":[
      {
         "attribute_code":"address",
         "value":"st"
      },
      {
         "attribute_code":"city",
         "value":"st"
      },
      {
         "attribute_code":"job",
         "value":"test"
      }]
}

I need to get the value from the attribute_code that is equal city

I've tried this code:

if list["custom_attributes"]["attribute_code"] == "city" in list:
     var = list["value"]

But this gives me the following error:

TypeError: list indices must be integers or slices, not str

What i'm doing wrong here? I've read this solution and this solution but din't understood how to access each value.

CodePudding user response:

Another solution, using next():

dct = {
    "id": 1,
    "name": "John",
    "status": 2,
    "custom_attributes": [
        {"attribute_code": "address", "value": "st"},
        {"attribute_code": "city", "value": "st"},
        {"attribute_code": "job", "value": "test"},
    ],
}

val = next(d["value"] for d in dct["custom_attributes"] if d["attribute_code"] == "city")
print(val)

Prints:

st

CodePudding user response:

Your data is a dict not a list.
You need to scan the attributes according the criteria you mentioned.
See below:

data = {

    "id": 1,
    "name": "John",
    "status": 2,
    "custom_attributes": [
        {
            "attribute_code": "address",
            "value": "st"
        },
        {
            "attribute_code": "city",
            "value": "st"
        },
        {
            "attribute_code": "job",
            "value": "test"
        }]
}

for attr in data['custom_attributes']:
    if attr['attribute_code'] == 'city':
        print(attr['value'])
        break

output

st
  • Related