Burn_jacks
Burn_jacks

Reputation: 45

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!

Upvotes: 1

Views: 180

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195553

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}}

Upvotes: 1

Related Questions