Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python 3.x loop through an array find the repeating elements and sum them into a new element

hi i’ve been trying to find a way to find the sum of the repeating elements within an array.

I have this array of data and I would like to find a way to go through it and find the sum of the elements that are repeated.

data_set = [{'service_general_id': 46, 'service_general_qty': 1000.0}, {'service_general_id': 46, 'service_general_qty': 56000.0}, {'service_general_id': 44, 'service_general_qty': 56000.0}]

the result that I have in mind is something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data_result = [{'service_general_id': 46, 'service_general_qty': 57000.0}, {'service_general_id': 44, 'service_general_qty': 56000.0}]

I’ve been trying to go through this way to find the repeats.

        for servicio in provisiones_originales_dict:
            k, v = servicio['servicio_general_id'], servicio['servicio_general_qty']

but I have not found the logic to find the repeated ones and add them in a result array

>Solution :

You can first create dict base on service_general_id as key then compute sum then convert to result dict like below:

>>> data_set = [{'service_general_id': 46, 'service_general_qty': 1000.0}, {'service_general_id': 46, 'service_general_qty': 56000.0}, {'service_general_id': 44, 'service_general_qty': 56000.0}]

>>> dct = {}
>>> for (key ,value) in (dct.values() for dct in data_set):
...    dct[key] = value + dct.get(key,0)
>>> dct
{46: 57000.0, 44: 56000.0}
    
>>> res = [{'service_general_id':key , 'service_general_qty':value} for key, value in dct.items()]
>>> res
[{'service_general_id': 46, 'service_general_qty': 57000.0},
 {'service_general_id': 44, 'service_general_qty': 56000.0}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading