I have a file with two columns of data, for example:
JavaScript
x
7
1
1 5
2
1 6
3
2 3
4
3 4
5
3 5
6
7
I want to obtain a dictionary with first column as the key and the second column as values, something like the following:
JavaScript
1
2
1
B = {1 : [5,6], 2: [3], 3: [4,5]}
2
Advertisement
Answer
You haven’t specified full details of the content of your file. I am assuming you don’t have any column names. With that if you use pandas, the solution will look like:
JavaScript
1
4
1
import pandas as pd
2
df = pd.read_fwf('example.txt', header=None)
3
out = df.groupby(0).agg(list).to_dict()[1]
4
read_fwf
is used to read fixed width format files. the option header=None
makes sure that the first row is not taken as column names.
Then you groupby the first column and aggregate the second column as list. Then use to_dict()
to get a dictionary.
print(out):
JavaScript
1
2
1
{1: [5, 6], 2: [3], 3: [4, 5]}
2