简体   繁体   中英

Creating dictionary from CSV file,

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.

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]} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM