Search code examples
python-3.xlistdictionary

How to compare list of dicts in Python


I have below list:

objList = [{
            'Name': 'keyboard',
            'objectId': [0, 1],
            'StartTime': '2022-01-10T13:18:17.098119',
            'IsCompleted': False,
            'MetaData': [{
                'Count': 2
            }]
}]


o = [{"keyboard": "Assembly"}, {"smallObjects": "Label"}]

I have to check if objList has all the dict with Name matching the key of dict in o. If not then print the Name. I have below working code:

if len(objList) != len(o):
    for i in o:
        for (k, v) in i.items():
            for obj in objList:
                if k == obj["Name"]:
                    print("Found {}".format(k))
                else:
                    print("Not found {}".format(k))

It seems to be working but not properly optimized as it has lot of for loop. Is there any other way we can optimize the code?


Solution

  • another way to resolve your problem is to trap all keys and all values for key Name in 2 sets/lists, like this:

    objList = [{
                'Name': 'keyboard',
                'objectId': [0, 1],
                'StartTime': '2022-01-10T13:18:17.098119',
                'IsCompleted': False,
                'MetaData': [{
                    'Count': 2
                }]
    }]
    o = [{"keyboard": "Assembly"}, {"smallObjects": "Label"}]
    
    all_keys = set().union(*(d.keys() for d in o))
    names=[d['Name'] for d in objList]
    
    for k in all_keys:
        if k in names:
            print("Found {}".format(k))
        else:
            print("Not found {}".format(k))