P
P
pcdesign2021-08-06 14:06:59
Python
pcdesign, 2021-08-06 14:06:59

What is the most efficient way to calculate the index of an element in a nested structure?

Here is the structure

my_list = {"groups":[
  {
    "descr":"3 светильника из профиля Люкс",
    "zones":[
      {
        "id":"2dd1fd73-7ed5-41be-90f3-2ff904f7b600",
        "descr":"Профиль 4970, 4-х рядная лента, управление."
      }
    ],
    "id":"93145ca7-f284-46d2-98ed-ad187ad3b996"
  },
  {
    "descr":"6, жилая комната",
    "zones":[
      {
        "id":"f0621e80-ecc9-4148-a689-c7c36e416ce0",
        "descr":"Лента, блок"
      },
      {
        "id":"083721b6-a8b7-470a-8162-6399e0cd90e2",
        "descr":"Лента,блок"
      }
    ],
    "id":"de1b4ad5-6f07-473b-88bc-fe2f93cfbafb"
  },
  {
    "descr":"5,жилая комната",
    "zones":[
      {
        "id":"3441ef59-bf85-4303-a4cc-6105cdf4cf9a",
        "descr":"Лента,блок"
      }
    ],
    "id":"b6d76ada-2c40-45bb-8ad6-295a579aad9e"
  },
  {
    "descr":"4,жилая комната",
    "zones":[
      {
        "id":"c4973844-76c4-479f-a5ac-1298e5dd6259",
        "descr":"Лента,блок"
      },
      {
        "id":"2068c560-2255-4487-bf5c-0904b830227f",
        "descr":"Лента,блок"
      }
    ],
    "id":"24a8fb7e-68ac-42f5-8217-b9315a407535"
  }
]
}



For example, I need to find the index of an element with a specific ID and with a specific parent ID.

Then the solution is like this:
for row in my_list['groups']:
    if row['id'] == 'de1b4ad5-6f07-473b-88bc-fe2f93cfbafb':
        for i, item in enumerate(row['zones']):
            if item['id'] == '083721b6-a8b7-470a-8162-6399e0cd90e2':
                print('index=', i)


Is there a way to do it better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Larisa .•º, 2021-08-06
@barolina

nested-lookup
or
recursion

V
Vindicar, 2021-08-06
@Vindicar

If you build a data structure once, and then run a series of such queries on it, it may make sense to loop through the entire structure and build a dictionary of the following kind.
Key: tuple (parent_id, element_id)
Value: element data
Then, when querying, it will be possible to construct the same tuple, and then check its presence in the dictionary or retrieve the element from the dictionary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question