0

I have a CSV like this:

(row 0)    key1   key2   key3
(row 1)    A      D      G
(row 2)    B      E      H
(row 3)    C             I

I want to read it and get the information into a dictionary as follows: dict = {key1: ["A", "B", "C"], key2: ["D", "E"], key3: ["G", "H", "I"]}.

So basically I want to have the first row as keys and all the values per column as values of a list (the list is the value of the key in the dictionary).

Thank you!

1 Answer 1

1

You could stack and groupby aggregating the values to a list, and turn to a dictionary with .to_dict():

df = pd.read_csv("my_csv.csv")
df.stack().groupby(level=1).agg(list).to_dict()
# {'key1': ['A', 'B', 'C'], 'key2': ['D', 'E'], 'key3': ['G', 'H', 'I']}
Sign up to request clarification or add additional context in comments.

2 Comments

in question, I is in key3 not in key2
Yes, that's just for how I read the string @oreopot Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.