Home > Software engineering >  Python: Create dictionary from table on file with variable columns
Python: Create dictionary from table on file with variable columns

Time:07-25

If I have a file data.txt looking like

a 1
b 2
c 3

Running the code

file = open('data.txt')
foo = dict([line.split() for line in file])

Creates a dictionary

{'a': 1, 'b': 2, 'c': 3}

I find this quite elegant. Suppose I have now a file data_vec.txt looking like

a 1 2 3
b 2
c 3

I would like to do the same as above to have in output the dictionary

    {'a': [1, 2, 3], 'b': 2, 'c': 3}

The code above won't work with lines of different length. I can obtain the desired output by writing

file = open('data_vec.txt')
foo = dict()
for line in file:
        split_line = line.split()
        foo[split_line[0]] = split_line[1:]

but I don't think it's as elegant a solution as the one above for the two-column file. Is there anything more pythonic that could be done?

Edit Would

foo = dict([[line.split()[0], line.split()[1:]] for line in file])

be acceptable? If not, why?

CodePudding user response:

Use extended iterable unpacking with a dictionary comprehension:

with open('data_vec.txt') as file:
    foo = {key: values for key, *values in map(str.split, file)}
    print(foo)

Output

{'a': ['1', '2', '3'], 'b': ['2'], 'c': ['3']}
  • Related