如何将多行字符串解析为python dict?
我已经开始了我的第一个编程项目,尝试用Python收集传感器读数 我已经设法将“ipmitool传感器列表”的输出作为字符串存储到变量中。 我想在dict中将前两列存储为key和value时遍历该字符串 print myvariable的输出如下所示:如何将多行字符串解析为python dict?,python,dictionary,Python,Dictionary,我已经开始了我的第一个编程项目,尝试用Python收集传感器读数 我已经设法将“ipmitool传感器列表”的输出作为字符串存储到变量中。 我想在dict中将前两列存储为key和value时遍历该字符串 print myvariable的输出如下所示: CPU Temp | 26.000 | degrees C | ok System Temp | 23.000 | degrees C | ok Peripheral Te
CPU Temp | 26.000 | degrees C | ok
System Temp | 23.000 | degrees C | ok
Peripheral Temp | 30.000 | degrees C | ok
PCH Temp | 42.000 | degrees C | ok
我希望字典看起来像
{'CPU Temp':26.000,'System Temp':23.000}
等如果没有转义,请从[line.split(“|”)开始,表示数据中的行。splitlines()
如果有棘手的字符和转义规则,您需要使用
csv
模块对其进行解析:您可以执行以下操作:
a_string ="""CPU Temp | 26.000 | degrees C | ok
System Temp | 23.000 | degrees C | ok
Peripheral Temp | 30.000 | degrees C | ok
PCH Temp | 42.000 | degrees C | ok"""
a_dict = {key.strip():float(temp.strip()) for key, temp, *rest in map(lambda v: v.split('|'), a_string.splitlines())}
print(a_dict)
给出:
{'Peripheral Temp': 30.0, 'System Temp': 23.0, 'CPU Temp': 26.0, 'PCH Temp': 42.0}
对于python 2:
a_dict = {v[0].strip():float(v[1].strip()) for v in map(lambda v: v.split('|'), a_string.splitlines())}
这看起来很棒!但是由于某种原因,我在*rest下得到了一个带有“^”的语法错误。@Chris我为python 2添加了一个版本。对于将来,最好指明您使用的python版本。Python2和Python3不兼容。请注意,以备将来参考!谢谢Marcin
import itertools
string_to_split = """CPU Temp | 26.000 | degrees C | ok
System Temp | 23.000 | degrees C | ok
Peripheral Temp | 30.000 | degrees C | ok
PCH Temp | 42.000 | degrees C | ok"""
list_of_lines = string_to_split.split('\n')
list_of_strings = []
final_list = []
for index in range(0, len(list_of_lines)):
try:
final_list.append(list_of_lines[index].split('|')[0])
final_list.append(list_of_lines[index].split('|')[1])
except Exception, e:
print e
dic_list = iter(final_list)
dic = dict(zip(dic_list, dic_list))
print dic