Home > Enterprise >  Searching a prefix in list of dictionaries in python
Searching a prefix in list of dictionaries in python

Time:11-17

I have currently a list of dictionaries

list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                 {"name": 'stfdahbancssc',"status":'running'}]

I want to check how can i match the prefix 'stf' and print stf exists otherwise stf does not exist .

CodePudding user response:

Iterate the dictionaries, get the "name" value, check for prefix, print message:

list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                {"name": 'stfdahbancssc',"status":'running'},
                {"name": 'none'}]

for idx,d in enumerate(list_of_dicts): 
    if d.get("name","").startswith("stf"):
        v = d["name"]
        s = d["status"]
        print(f"The {idx} dictionary has {v} as {s}")
        print("a")
    else:
        print(f"The {idx}. dictionary has no name starting with 'stf'.")    

Output:

  • Related