'Find a specific key in python dictionary inside a list

I have a list of dictionaries and I am looking to get a specific key at a certain index

[
   {
      "id":"23fr3yf48",
      "type":"engine",
      "details":{
         "text":"New",
         "type":"SPT_2048",
         "id":"7033_Q-156",
         "engine_details":{
            "dateCreated":"2021-08-13 08:59:32.870953+00:00",
            "createdBy":"John",
         },
      },
      "confirm":true
   },
   {
      "id":"3u823983hf",
      "type":"wheel",
      "details":{
         "text":"Old",
         "type":"SPT_0006",
         "id":"101841_2004497"
      },
      "confirm":true
   },
]

In this JSON I want to get the 'id' inside 'details' dict. I specifically want to get the 'details' from the index 1 that has id - '101841_2004497' skipping the 0th index. I want to know to iterate through the list and find the specific index. Can someone help me with this?



Solution 1:[1]

This is a simple for loop to check each item in list if the id of its details is equal to the value which you mentioned: 101841_2004497

for item in list:
    if item["details"]["id"] == "101841_2004497":
        print(item["details"])

JSON response:

{'text': 'Old', 'type': 'SPT_0006', 'id': '101841_2004497'}

Hope it helps!

Solution 2:[2]

You don't need to iterate through the list - you can directly access an item by its index. See, for example the Python tutorial.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Indriti
Solution 2 ndc85430