0

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.

OdiumPura
  • 444
  • 5
  • 25
  • 1
    That's not a list. – no comment Sep 23 '21 at 16:55
  • I've used a `json.loads`, this is not a list? – OdiumPura Sep 23 '21 at 16:58
  • 1
    No, it's a dictionary. – no comment Sep 23 '21 at 16:59
  • I'll though this was a list of dictionaries because have dictionaries within it. But ok, I'll try to find a reference to understand the difference between them. – OdiumPura Sep 23 '21 at 17:02
  • 1
    You have a dictionary - let's call it **D**. You can access keys in a dictionary directly. You cannot access values in a dictionary directly. D['custom_attributes'] is a list of dictionaries. Each element in that list is a dictionary. You can use the dictionary built-in function *items()* to work through each of those dictionaries to try to find what you're looking for –  Sep 23 '21 at 17:03
  • @DarkKnight Thanks, now I understood! – OdiumPura Sep 23 '21 at 17:05

2 Answers2

3

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

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
balderman
  • 22,927
  • 7
  • 34
  • 52