Search code examples
dictionaryparsingpython-3.7

Multi-line text input to dictionary


Say I've got a multi-line input from a text file that looks smth like this:

(empty string here)
1 -30 2 0
3 0 5 10

etc.

I parsed the input and formed a list out of it:

lst = [[], [(1, -30), (2, 0)], [(3, 0), (5, 10)]]

Assume I want to make a dictionary where the key is the line number (starting with 1) and the value is a nested dictionary which contains the first element of a tuple as a key and the second one as a value:

**lst -> dict:**
dict = {'1': {}, '2': {1: -30, 2: 0}, '3': {3: 0, 5: 10}}

What's the best (pythonic) way to do this? Spent couple hours by now trying to do this. Thanks!


Solution

  • lst = [[], [(1, -30), (2, 0)], [(3, 0), (5, 10)]]
    
    print( {str(i): dict(v) for i, v in enumerate(lst, 1)} )
    

    Prints:

    {'1': {}, '2': {1: -30, 2: 0}, '3': {3: 0, 5: 10}}