Skip to content
Advertisement

How to compare a list of dict with list of tuples in Python

I have a list of dict as below:

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

and list of tuples:

objectsCounter = [('keyboard', 2), ('smallObjects', 4)]

I have to write a python code where I have to checkif MetaData from dict (for both keyboard & smallObjects) in objList if greater than or equal to the count in objectsCounter. If yes, then I have to set IsCompleted to True otherwise False. For this I have written below code and its working fine

for obj1 in objList:
    for obj2 in objectsCounter:
        if obj2[0] == obj1['Name']:
            if obj2[1] >= obj1['MetaData'][0]['Count']:
                obj1['IsCompleted'] = True
                
            break

But because I am using lot of for and if, I feel there must be a better way to do this comparison. Can anyone help me in optimizing the above code or does above code looks fine. Thanks

Advertisement

Answer

I think your solution works pretty well, here is another way of doing it. Turn your objectsCounter into a Dictionary and then loop through only one list

o=dict(objectsCounter )

for i in objList:
  #Matching your code
  i['IsCompleted']= o[i['Name']] >= i['MetaData'][0]['Count']

You will only loop through the items you need, ie those in objList. You also don’t need if when you just set the value for isCompleted to the logical comparison.

To match the description not code just change the operator

      i['IsCompleted']= o[i['Name']] <= i['MetaData'][0]['Count']
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement