Skip to content
Advertisement

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]}

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:

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]}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement