add numbers from Different dicts in for loop
Question:
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:
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
Answers:
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}}}
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:
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
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}}}