+3 votes
in Programming Languages by (77.8k points)
I have an input CSV file with two columns. I want to read the file and convert its content into a dictionary with one column as keys and another as values. What is the Pythonic way to do this?

1 Answer

+3 votes
by (73.6k points)
selected by
 
Best answer

You can try one of the following two approaches:

Here I am reading a tab-separated CSV file. If you have a comma or semicolon as the separator, you can modify the code accordingly.

Approach 1

with open("yourfile.csv", "r") as fin:

    v_dict = {v.strip().split('\t')[0]: v.strip().split('\t')[1] for v in fin}

Approach 2

with open("yourfile.csv", "r") as fin:

    v_dict = dict(line.strip().split('\t') for line in fin)


...