1

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?

0

1 Answer 1

1

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']}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.