Home > Back-end >  Python search for all nested values in list of dictionaries that matches a nested key
Python search for all nested values in list of dictionaries that matches a nested key

Time:05-10

I have the following list of dictionaries:

data = [
    {
        "connections": None
    },
    {
        "connections": {
            "endpoints": [
                {
                    "id": "ee0d38d3-89fb-4e5b-b9bd-83ee554949ab",
                    "vlan": 200,
                },
                {
                    "id": "192ee48f-ad20-48ad-acae-9c8d33e4687b",
                    "vlan": 100,
                },
            ]
        }
    },
    {
        "connections": {
            "endpoints": [
                {
                    "id": "4e6b8844-9a91-4098-aa92-ef97ce89cbed",
                    "vlan": 200,
                },
                {
                    "id": "577fcb45-57ab-4903-be60-5b8ac84b8a09",
                    "vlan": 100,
                },
            ]
        }
    },
]

I want to search for 'id' "ee0d38d3-89fb-4e5b-b9bd-83ee554949ab" in data and extract all the vlans for any matching 'id'. So in this example, my resulting variable should only contain a list of matches as such:

[100]

I say a list because it is possible that 'id' "ee0d38d3-89fb-4e5b-b9bd-83ee554949ab" will also have another entry in data but with a different vlan. So you could end up with in my result:

[200, 300]

I tried the following but I get a "TypeError: 'NoneType' object is not subscriptable":

vlans = [d["connections"]["endpoints"]["vlan"] for d in data if d["connections"]["endpoints"]["id"] == id]

CodePudding user response:

You do something like below:

res = [endpoint['vlan'] for item in data if item["connections"] for endpoint in item["connections"]["endpoints"] if endpoint['id']== "ee0d38d3-89fb-4e5b-b9bd-83ee554949ab"]

and if you need unique vlan values you can use

list(set(res))
  • Related