Reputation: 391
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?
Upvotes: 0
Views: 1367
Reputation: 78546
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.
Upvotes: 2
Reputation: 6111
res = {}
with open('foo.csv') as f:
reader = csv.reader(f)
for i,item in enumerate(reader):
if i == 0: continue
a,b = item[0],item[1:]
if a not in res:
res[a] = {}
res[a].update( {b[0]:b[1]} )
Upvotes: 0