How to append items in dictionary nested list?


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]}
Asked By: Raghvender



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.


{1: [5, 6], 2: [3], 3: [4, 5]}
Answered By: SomeDude

try this:

df.groupby("column_name").apply(lambda x:x.values.flatten().tolist()).to_dict()
Answered By: to_data
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.