For the following CSV File:
A,B,C
A1,B1,C1
A1,B2,C2
A2,B3,C3
A2,B4,C4
How do I get my dictionary to look like this:
{'A1': {'B1': 'C1', 'B2' : 'C2'}, 'A2': {'B3': 'C3', 'B4' : 'C4'}}
I'm using the following code:-
EgDict = {}
with open('foo.csv') as f:
reader = csv.DictReader(f)
for row in reader:
key = row.pop('A')
if '-' in key:
continue
if key not in result:
new_row = {row.pop('B'): row.pop('C')}
result[key] = new_row
else:
result[key][row.pop('B')].append(row.pop('C'))
I'm getting the following error:-
AttributeError: 'dict' object has no attribute 'append'
What Am I doing wrong here?
A dictionary has no append
method. That will be for lists.
You may consider using the following code instead:
d = {}
with open('foo.csv') as f:
reader = csv.DictReader(f)
for row in reader:
d.setdefault(row['A'], {}).update({row['B']: row['C']})
print(d)
# {'A1': {'B1': 'C1', 'B2' : 'C2'}, 'A2': {'B3': 'C3', 'B4' : 'C4'}}
setdefault
sets a new key with a default {}
value when one does not exist and the update methods updates the dictionary at that key using the new values.