Home > Back-end >  Convert dict to lists by using substrings
Convert dict to lists by using substrings

Time:04-13

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?

CodePudding user response:

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]}

CodePudding user response:

You can check if the key name contains HVAC or DHW. Create a list and append the values in their respective list.

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
}

HVAC_flex, DHW_flex = [], []
for k,v in d.items():
    if "HVAC" in k:
        HVAC_flex.append(v)
    else: 
        DHW_flex.append(v)
print(HVAC_flex)
print(DHW_flex)

I'm using else because there are only two substrings in your dictionary but if they contain more try getting the text before square brackets:

prefix = []
for k,v in d.items():
    if k.split('[')[0] not in prefix: # this splits the string into part containing '[' by using [0] we get the string part. 
        prefix.append(k.split('[')[0])
    else:
        continue

Output:

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