Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if key is present in list of dictionaries and if true return dictionary index in list

I have a list of dictionaries and I’m trying to check if there is a key in each dictionary called ‘tag’ with a value of ‘staging automator’. If this is true then create a new list with just those dictionaries.

    "entry": [
    {
        "@location": "vsys",
        "@name": "reactor-test",
        "@vsys": "vsys1",
        "dynamic": {
            "filter": "'reactor' or 'ACI-Reactor_epg'"
        },
        "tag": {
            "member": [
                "reactor"
            ]
        }
    },
    {
        "@location": "vsys",
        "@name": "Customer Access",
        "@vsys": "vsys1",
        "description": "Allowed addresses for external customers",
        "static": {
            "member": [
                "GG-sub"
            ]
        }
    },
    {
        "@location": "vsys",
        "@name": "test-dynamic-group",
        "@vsys": "vsys1",
        "dynamic": {
            "filter": "'staging-automator'"
        }
    },
    {
        "@location": "vsys",
        "@name": "MyDynamicGroup",
        "@vsys": "vsys1",
        "description": "I edited this via postman because I'm cool.",
        "dynamic": {
            "filter": "staging-automator"
        },
        "tag": {
            "member": [
                "staging-automator"
            ]
        }
    }
]

So far I’ve come up with this which will tell me which dictionaries in the list contain what I’m looking for:

for item in myList:
    if "tag" in item.keys():
        if item["tag"]["member"][0] == "staging-automator":
            print("True")
        else:
            print("False")
    else:
        print("False")

But I’m stuck with how to then grab that dictionary out of the list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Hope it helps:

new_list = []
for item in your_dictionaries:
    if "tag" in item.keys():
        if item["tag"]["member"][0] == "staging-automator":
            new_list.append(item)
print(new_list)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading