Search code examples
pythonlistdictionarysubstring

Convert dict to lists by using substrings


I have the following dict:

dict = {
    "HVAC_flex[1,1]": 8.0,
    "HVAC_flex[1,2]": 15.0,
    "HVAC_flex[2,1]": 0.0,
    "HVAC_flex[2,2]": 0.0,
    "DHW_flex[1,1]": 0.0,
    "DHW_flex[1,2]": 2.0,
    "DHW_flex[2,1]": 4.0,
    "DHW_flex[2,2]": 17.0
}

And what I would like to produce is two lists as follows:

HVAC_flex = [ 8.0, 15.0, 0.0, 0.0]
DHW_flex = [ 0.0, 2.0, 4.0, 17.0]

The thing is that the dimensions are dynamically defined, so the dict may include additional values.

My idea is to search for substrings, like if HVAC_flex is inluded in the key, then put the value into this list, etc, but I could find a clever way to implement this. Is there a way to do this?


Solution

  • You cannot create those "named" lists - you can however use a list comprehension to create a list of list of values:

    d = {
        "HVAC_flex[1,1]": 8.0,
        "HVAC_flex[1,2]": 15.0,
        "HVAC_flex[2,1]": 0.0,
        "HVAC_flex[2,2]": 0.0,
        "DHW_flex[1,1]": 0.0,
        "DHW_flex[1,2]": 2.0,
        "DHW_flex[2,1]": 4.0,
        "DHW_flex[2,2]": 17.0
    }
    
    prefix = ["HVAC", "DHW"]
    
    values = [ [v for key,v in d.items() if key.startswith(b)] for b in prefix ]
    
    print(values)
    

    Output:

    [[8.0, 15.0, 0.0, 0.0], [0.0, 2.0, 4.0, 17.0]]
    

    It would probably make more sense to use a dict comprehension to create another dict:

    values = {b: [v for key,v in d.items() if key.startswith(b)] for b in prefix }
    
    print(values)
    

    to keep the information about the prefix:

    {'HVAC': [8.0, 15.0, 0.0, 0.0], 'DHW': [0.0, 2.0, 4.0, 17.0]}