Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Create dictionary from table on file with variable columns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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?

>Solution :

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']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading