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

Convert dictionary to dictionary of lists by using strings

I have data in the following form:

{None: {'VPP_users': {None: [1, 2, 3, 4]}, 'timesteps': {None: [1, 2]}, 'DR_signal': {None: 180.0}, 'power_contract': {(1, 1): 25, (2, 1): 78, (3, 1): 95, (4, 1): 9, (1, 2): 91, (2, 2): 62, (3, 2): 92, (4, 2): 52}, 'HVAC_flex_available': {(1, 1): 5, (2, 1): 24, (3, 1): 28, (4, 1): 9, (1, 2): 14, (2, 2): 25, (3, 2): 10, (4, 2): 50}, 'DHW_flex_available': {(1, 1): 46, (2, 1): 27, (3, 1): 27, (4, 1): 6, (1, 2): 10, (2, 2): 10, (3, 2): 27, (4, 2): 22}}}

I need somehow to modify the above form in the following form:

{'HVAC_flex_available': [5, 24, 28, 9, 14, 25, 10, 50], 'DHW_flex_available': [46, 27, 27, 6, 10, 10, 27, 22]}

Specifically, I want to get the variables HVAC_flex_available and DHW_flex_available and keep the numbers after the indices (1,1), (2,1), etc.

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

Any idea of how can I implement it?

EDIT: What I have tried until now is the following:

prefix = ["HVAC_flex_available", "DHW_flex_Avaliable"] 
output = {b: [v for key,v in solution.items() if key.startswith(b)] for b in prefix 

But I am getting:

AttributeError: 'NoneType' object has no attribute 'startswith'

>Solution :

You can achieve this with dictionary comprehension, considering the exact format of this input dictionary :

d = {None: {'VPP_users': {None: [1, 2, 3, 4]}, 'timesteps': {None: [1, 2]}, 'DR_signal': {None: 180.0}, 'power_contract': {(1, 1): 25, (2, 1): 78, (3, 1): 95, (4, 1): 9, (1, 2): 91, (2, 2): 62, (3, 2): 92, (4, 2): 52}, 'HVAC_flex_available': {(1, 1): 5, (2, 1): 24, (3, 1): 28, (4, 1): 9, (1, 2): 14, (2, 2): 25, (3, 2): 10, (4, 2): 50}, 'DHW_flex_available': {(1, 1): 46, (2, 1): 27, (3, 1): 27, (4, 1): 6, (1, 2): 10, (2, 2): 10, (3, 2): 27, (4, 2): 22}}}
d2 = {key:[v for v in d[None][key].values()] for key in ['HVAC_flex_available', 'DHW_flex_available']}

# Output
{'HVAC_flex_available': [5, 24, 28, 9, 14, 25, 10, 50], 'DHW_flex_available': [46, 27, 27, 6, 10, 10, 27, 22]}
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