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

add numbers from Different dicts in for loop

i have here this dict :

dict = {
    "A": {
        "value": 5
    },
    "B": {
        "value": -3
    },
    "C": {
        "value": -2
    },
    "D":{
        "value": 2
    },
    "E":{
        "value": -2
    }

}

i want To collect all the values
and sum it up when it equals 0

to be 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


newDict = {
    "0": {
        # A + B + C = 0 , so combine it togather
        # 5 + -3 + -2 = 0
        "A":{
            "value": 5
        },
        "B": {
            "value": -3
        },
        "C": {
            "value": -2
        },
    },
    # when its = 0 start new dict
    "1":{
         # D + E = 0 , so combine it togather
         # 2 + -2 = 0
         "D":{
            "value": 2
        },
        "E":{
            "value": -2
        }
    },
    # etc....

i hope its a clear question
this is my first time on stackover flow
thank u all

>Solution :

The simple idea is to first use a list to store the split dictionary, and then use the dictionary comprehension to build the result after splitting:

>>> mp
{'A': {'value': 5},
 'B': {'value': -3},
 'C': {'value': -2},
 'D': {'value': 2},
 'E': {'value': -2}}
>>> mp_lst = []
>>> val_sum = 0
>>> for k, v in mp.items():
...     if not val_sum:
...         mp_lst.append({})
...     val_sum += v['value']
...     mp_lst[-1][k] = v
...
>>> {str(i): elem for i, elem in enumerate(mp_lst)}
{'0': {'A': {'value': 5}, 'B': {'value': -3}, 'C': {'value': -2}},
 '1': {'D': {'value': 2}, 'E': {'value': -2}}}
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