Reputation: 3
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!
Upvotes: 0
Views: 276
Reputation: 88236
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']}
Upvotes: 1