简体   繁体   中英

How do I parse a multiline string into a python dict?

I've started my very first programming project by trying collect sensor readings in Python.

I've managed to store the output of "ipmitool sensors list" as a string into a variable. I've like to go through that string at store the first 2 columns as key, value in a dict.

The output of print myvariable looks something like this:

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    

I'd like the dictionary to look like {'CPU Temp': 26.000, 'System Temp': 23.000} etc

You could do as follows:

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)

Gives:

{'Peripheral Temp': 30.0, 'System Temp': 23.0, 'CPU Temp': 26.0, 'PCH Temp': 42.0}

For python 2:

a_dict  = {v[0].strip():float(v[1].strip()) for v in map(lambda v: v.split('|'), a_string.splitlines())}

If there is no escaping, start with [line.split("|") for line in data.splitlines()] .

If there are tricky characters and escaping rules, you'll want to use the csv module to parse it: https://docs.python.org/2/library/csv.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM