Skip to content
Advertisement

Python convert switch data (text) to dict

I have the following data, which I recieve via a ssh session to a switch. I wish to convert the input which is text to a dict for easy access and the possiblity to monitor certain values.

I cannot get the data extracted without a ton of splits and regexes and still get stuck.

JavaScript

Which I want to convert to:

JavaScript

Advertisement

Answer

Updated (Complete rewrite and simplification).

Here are some ideas for you — adjust to taste.

The solution herein tries to avoid using “domain specific knowledge” as much as possible. The only assumptions are:

  1. Empty lines don’t matter.
  2. Indentation is meaningful.
  3. Keys are transformed to lowercase, and some content is removed (stuff in parentheses, 'name', 'threshold', and /...).
  4. When a line has multiple “key : value” pairs or is followed by an indented group of lines, that is a block of information pertaining to the first key.

Ultimately, when a key has multiple values (e.g. 'port'), then these values are put together as a list. When a key has a value that is a single dict (like for 'temp'), then the first key of that dict (the same as the key itself) is replaced by 'value'. Thus, we will see:

  • {'port': [{'port': 1, ...}, {'port': 2, ...}, ...]}, but
  • {'temp': {'value': 37, ...}}.

Records

We start by splitting each line into (key, value) pairs and note the indentation of the line. The result is a list of records, each containing: (indent, [(k0, v0), ...]):

JavaScript

Example on your text:

JavaScript

Note that not only keys but also values may contain spaces (e.g. 'Wavelength : 850 nm'). We decided to use the largest space to split intermediary '{v[i] k[i+]}' substrings. Thus:

JavaScript

Blocks

We then construct a hierarchical representation of the records in way that takes indentation into account:

JavaScript

Example on the records above (obtained from your txt):

JavaScript

Note the repeated first key in sub blocks (e.g. ('port', [('port', 1), ...]) and ('temp', [('temp', 37.0), ...]).

Final structure

We then transform the blocks hierarchical structure into a dict, with some ad-hoc logic (no clobbering (k, v) pairs that have the same key, etc.). And finally put all the pieces together in a proc_txt() function:

JavaScript

Example on your text

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement