How to create dict of dicts using csv file


How to create dict of dicts using csv file
I'd like to create a dictionary with the key's being the first row of the csv file and the value's being a dictionary of first column: corresponding column to row For example, test.csv
Header1, Header2, Header3
A, 1, 10
B, 2, 20
C, 3, 30
I am using data.drop(['Header1'], 1)
to drop Header1
.
data.drop(['Header1'], 1)
Header1
I would like the resulting dict to be:
'Header2':A:1, B:2, C:3,'Header3':A:10, B:20, C:30
Should I be using csv.DictReader
? Or numpy arrays instead?
csv.DictReader
'Header2':A:1, B:2, C:3,'Header3':A:10, B:20, C:30
Yes, thank you.
– csanders1999
2 days ago
Just do
to_dict
– RafaelC
2 days ago
to_dict
If your issue is resolved please mark one of the answers as correct
– mrangry777
2 days ago
2 Answers
2
Using pandas,
df = pd.read_csv(testcsv, index_col=['Header1'], sep=',s+')
df.to_dict()
Output:
'Header2': 'A': 1, 'B': 2, 'C': 3, 'Header3': 'A': 10, 'B': 20, 'C': 30
This is saying ValueError: Index Header1 invalid?
– csanders1999
2 days ago
Try
index_col=[0]
because it doesn't appear your csv first column is 'Header1'.– Scott Boston
2 days ago
index_col=[0]
Another example without pandas:
import csv
with open('data_all.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
dicts = entry: for entry in next(reader)[1:]
for row in reader:
index = 0
for _dict in dicts.values():
index+=1
_dict[row[0]]=row[index]
print(dicts)
' Header2': 'A': ' 1', 'B': ' 2', 'C': ' 3', ' Header3': 'A': ' 10', 'B': ' 20', 'C': ' 30'
' Header2': 'A': ' 1', 'B': ' 2', 'C': ' 3', ' Header3': 'A': ' 10', 'B': ' 20', 'C': ' 30'
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Dont you mean
'Header2':A:1, B:2, C:3,'Header3':A:10, B:20, C:30
?– mrangry777
2 days ago