It might be very simple but at the moment, I just don't find a solution for my problem.
I have a dictionary that looks like this:
list_of_pps = {'pp_coal': {'b_el': 20200},
'sto_simple': {'b_el': 200000},
'pp_gas': {'b_el': 41000},
'cable1': {'b_el2': 9000},
'cable2': {'b_el': 8000},
'pp_oil': {'b_el': 1000},
'pp_lig': {'b_el': 11800},
'pp_chp': {'b_th': None, 'b_el': 30000},
'pp_chp2': {'b_th': 25000, 'b_el': 25000}}
What I want is to sum up all numerical (not None) values on the second level (nested dict) of list_of_pps and assign them to the keys of the first level. This would look like this:
list_of_pps = {'pp_coal': 20200,
'pp_chp': 30000,
'pp_chp2': 50000,
'pp_lig': 11800,
'cable1': 9000,
'pp_gas': 41000,
'cable2': 8000,
'sto_simple': 200000,
'pp_oil': 1000}
I hope this makes it more understandable. What would be the best way to accomplish this?
Thanks in advance!
更新以反映新的问题数据:
clean_pps = {k: sum(filter(None, v.values())) for k, v in list_of_pps.items()}
>>> from pprint import pprint
>>> list_of_pps = dict((key, sum(v for v in value.values() if v is not None)) for key, value in list_of_pps.items())
>>> pprint(list_of_pps)
{'cable1': 9000,
'cable2': 8000,
'pp_chp': 30000,
'pp_chp2': 50000,
'pp_coal': 20200,
'pp_gas': 41000,
'pp_lig': 11800,
'pp_oil': 1000,
'sto_simple': 200000}
This is a possible implementation of dict_values
. That is, assuming I understand your question correctly.
def dict_values(l):
return [x for x in l if x is not None]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.