Find unique values in python list of dictionaries

Question:

I have a list with the following sample key value pairs:

results : {'ROI_0':[{'obj_id':1,'obj_name':'truck', 'obj_confi':93.55, 'bb_box': ['x','y','w','h']},
                    {'obj_id':2,'obj_name':'truck', 'obj_confi':91.35, 'bb_box': ['x','y','w','h']},
                    {'obj_id':3,'obj_name':'truck', 'obj_confi':92.65, 'bb_box': ['x','y','w','h']},
                    {'obj_id':4,'obj_name':'car', 'obj_confi':90.31, 'bb_box': ['x','y','w','h']},
                    {'obj_id':5,'obj_name':'car', 'obj_confi':90.31, 'bb_box': ['x','y','w','h']}
                   ]}

I need to obtain another list which looks like the one below:

aggreg_results : {'ROI_0':[{'obj_occurances': 3, 'obj_name': 'truck', 'obj_ids':[1,2,3]},
                           {'obj_occurances': 2, 'obj_name': 'car', 'obj_ids':[4,5]}
                          ]} 

Unable to figure out the logic to this.

Asked By: Chay

||

Answers:

My answer is a bit long, but I think its easier to understand.
First of all I will create a dict that have obj_name as unique key, then count all occurences and store the obj_ids

results = {'ROI_0':[{'obj_id':1,'obj_name':'truck', 'obj_confi':93.55, 'bb_box': ['x','y','w','h']},
                {'obj_id':2,'obj_name':'truck', 'obj_confi':91.35, 'bb_box': ['x','y','w','h']},
                {'obj_id':3,'obj_name':'truck', 'obj_confi':92.65, 'bb_box': ['x','y','w','h']},
                {'obj_id':4,'obj_name':'car', 'obj_confi':90.31, 'bb_box': ['x','y','w','h']},
                {'obj_id':5,'obj_name':'car', 'obj_confi':90.31, 'bb_box': ['x','y','w','h']}
               ]}
unique_items = dict()
for obj in results['ROI_0']:
    if obj['obj_name'] not in unique_items.keys():
        unique_items[obj['obj_name']] = {
            'obj_occurances': 0,
            'obj_ids': []
        }
    unique_items[obj['obj_name']]['obj_occurances'] += 1
    unique_items[obj['obj_name']]['obj_ids'].append(obj['obj_id'])

Now I have a dict like this in unique_items:

{
 'truck': {'obj_occurances': 3, 'obj_ids': [1, 2, 3]}, 
 'car': {'obj_occurances': 2, 'obj_ids': [4, 5]}
}

Then I just convert it into a dict as whatever format you want

aggreg_results = dict()
aggreg_results['ROI_0'] = list()
for k, v in unique_items.items():
    aggreg_results['ROI_0'].append({
        'obj_occurances': v['obj_occurances'],
        'obj_name': k,
        'obj_ids': v['obj_ids']
    })

Finally I get the the aggreg_results as you expected

{'ROI_0': [
           {'obj_occurances': 3, 'obj_name': 'truck', 'obj_ids': [1, 2, 3]},
           {'obj_occurances': 2, 'obj_name': 'car', 'obj_ids': [4, 5]}
          ]
}

I hope it helps!

Answered By: dinhit