使用子字符串将字典转换为列表
我有以下内容:
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
}
我想产生的是两个列表,如下所示:
HVAC_flex = [ 8.0, 15.0, 0.0, 0.0]
DHW_flex = [ 0.0, 2.0, 4.0, 17.0]
事实是,尺寸是动态定义的,因此dict
可能包括其他值。
我的想法是搜索substring,例如hvac_flex
被绑定在密钥中,然后将值放入此列表等,但是我可以找到一种巧妙的方法来实现此目标。有办法这样做吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法创建这些“命名”列表 - 但是您可以使用列表理解来创建值列表的列表:
输出:
使用字典理解来创建另一个字典可能更有意义:
保留有关前缀的信息:
You cannot create those "named" lists - you can however use a list comprehension to create a list of list of values:
Output:
It would probably make more sense to use a dict comprehension to create another dict:
to keep the information about the prefix:
您可以检查关键名称是否包含
HVAC
或DHW
。创建一个列表并在其各自列表中附加值。我正在使用
else
,因为您的字典中只有两个子字符串,但是如果它们包含更多的子字符串,请尝试在Square Brackets之前获取文本:输出:
You can check if the key name contains
HVAC
orDHW
. Create a list and append the values in their respective list.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:Output: