Reputation: 83
I have a file with two columns of data, for example:
1 5
1 6
2 3
3 4
3 5
...
I want to obtain a dictionary with first column as the key and the second column as values, something like the following:
B = {1 : [5,6], 2: [3], 3: [4,5]}
Upvotes: 0
Views: 70
Reputation: 1067
try this:
df.groupby("column_name").apply(lambda x:x.values.flatten().tolist()).to_dict()
Upvotes: 0
Reputation: 14228
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:
import pandas as pd
df = pd.read_fwf('example.txt', header=None)
out = df.groupby(0).agg(list).to_dict()[1]
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):
{1: [5, 6], 2: [3], 3: [4, 5]}
Upvotes: 2