0
category_list = ['cc18f344-7f94-4ce5-bfde-4031b21f2bf3', '632289ec-3c62-4133-be4d-5dab9112491b', '4ea7fd7e-ea95-4fb6-a62e-9835baa43a75', '8d6bea3d-3798-449d-930f-d56cf3f5d19f']

data = '{"language_code":"en_PK","vendor_id":"btqk","include_component_types":["multi_list"],"brand":"foodpanda","country_code":"pk","offset":0,"category_id":**%[n]**}'

i want to enter the index of category list in the Bold position, can anyone help me?

nikeros
  • 3,302
  • 2
  • 10
  • 26
Malik Zaib
  • 81
  • 1
  • 9
  • I think you can just say "I want to find the position in `category_list` of the `category_id` property", the bold characters do not make valid json – nikeros Dec 14 '21 at 12:03
  • bold characters are just a dummy data from the list written hardcoded, i cant seem to concatinate the index of list in the data string – Malik Zaib Dec 14 '21 at 12:06
  • Your question is not clear. With what exactly are you struggling? What research have you done to solve your problem? What have you tried already to solve this problem? – Tomerikoo Dec 14 '21 at 12:07
  • im trying to use the index of category_list in data within a loop, – Malik Zaib Dec 14 '21 at 12:10
  • the data is a string and i am not able to concatinate the index within data – Malik Zaib Dec 14 '21 at 12:11

2 Answers2

1

So if you have:

category_list = ['cc18f344-7f94-4ce5-bfde-4031b21f2bf3', '632289ec-3c62-4133-be4d-5dab9112491b', '4ea7fd7e-ea95-4fb6-a62e-9835baa43a75', '8d6bea3d-3798-449d-930f-d56cf3f5d19f']

data = '{"language_code":"en_PK","vendor_id":"btqk","include_component_types":["multi_list"],"brand":"foodpanda","country_code":"pk","offset":0,"category_id":"8d6bea3d-3798-449d-930f-d56cf3f5d19f"}'

You can simply lookup as follows:

import json

category_list.index(json.loads(data)["category_id"])

OUTPUT

3

Clearly, you need to managed situations when the category_id is not in category_list, and you can do it in different ways:

category_id = json.loads(data)["category_id"]
if category_id in category_list:
    print(category_list.index(category_id))

or you can catch the exception:

try:
    category_list.index(json.loads(data)["category_id"])
except ValueError:
    # Do what you need here
nikeros
  • 3,302
  • 2
  • 10
  • 26
0
if data["category_id"] in category_list:
    return category_list.index(data["category_id"])
else:
    return -1
benjababe
  • 91
  • 4
  • 2
    You can get rid of the `if` by replacing `index` with [`find`](https://docs.python.org/3/library/stdtypes.html#str.find) which already returns `-1` if the item is not found... – Tomerikoo Dec 14 '21 at 12:06