0
MQTT_MSG = {
"waypointMission":
{
    # "plantId": "OLD PLAN",
    "targetWaypoints":
    [
        {
            "latitude": 14.237372,
            "longitude": 77.457814,
            "threatLevel": 1,
            "timestamp": "",
            "waypointExecuted": 0,
            "waypointActions":
            [
                {
                    "action": "pitch",
                    "actionParam": -30
                },
                {
                    "action": "stay",
                    "actionParam": 3000
                }
            ]
        }
    ]}
print(MQTT_MSG['waypointMission']['targetWaypoints']['latitude'])

I want to change the value of the latitude and longitude of the dictionary.

It is throwing this error message:

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

For this print(MQTT_MSG['waypointMission']['targetWaypoints'][0]) It prints a full dictionary inside the targetWaypoints. I want to print latitude value.

Thanks in advance.

Gourav kumar
  • 23
  • 1
  • 2
  • 5

1 Answers1

0

This question is very similar to yours but without the added complication of the dict value being a list: Finding a key recursively in a dictionary Here's a modification of the code in the accepted answer to that question to deal with lists:

def recursive_search(target, key):
    if key in target:
        return target[key]
    for k, v in target.items():
        if isinstance(v, dict):
            item = recursive_search(v, key)
            if item is not None:
                return item
        elif isinstance(v, list):                #added code to handle the list
            for node in v:
                item = recursive_search(node, key)
                if item is not None:
                    return item

Testing this function:

recursive_search(MQTT_MSG, "latitude")
>>> 14.237372

Note that this will not do so well if there are duplicate keys at the same level (i.e. trying running it with "actionParam", it will only get the first value).

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11