Home > Software design >  Check if key is present in list of dictionaries and if true return dictionary index in list
Check if key is present in list of dictionaries and if true return dictionary index in list

Time:03-02

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.

CodePudding user response:

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)

CodePudding user response:

Inside the loop you already have your desired dictionary!

Where you are checking for the staging-automator, the item variable is your required thing; just append it to a new list.

Here's how it can be done

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

print(new_list)

CodePudding user response:

# a is the list of dict you have provided 
# Code by @Rishi
tag_list=[]
for i in a:
      if "tag" in i:
            if i["tag"]['member'][0]=="staging-automator":
                  tag_list.append(i)

Or use list comprehension:

b=[i for i in a if "tag" in i if i["tag"]['member'][0]=="staging-automator"]
print(b)

Explanation:

  • Just readed the items in the list,
  • checked if "tag" is present in the item,
  • if preset then again checked if tags:member's attributes is "staging-automator",
  • if that too is true then, i have appended it to the tag_list.

in searches if the given value is present in any data type for example in string, list, tuple ect.

List comprehension would be useful if you are having a large dict, as its faster than the normal for-loop.

CodePudding user response:

Use a filter instead of a loop.

def check_item(item):
    return "tag" in item and item["tag"]["member"][0] == "staging-automator"

list(filter(check_item, myList))
  • Related