简体   繁体   中英

How would I put a dict {key: value} in it's designated key in a dictionary so that it is {key: {key: value}} after counting value

I have a csv file where I am trying to count row[3] then connect it with row[0]

 row[0]      row[3]
 'A01'          'a'
 'B02'          'a'
 'A01'          'b'
 'A01'          'a'
 'B02'          'a'
 'A01'          'a'

so that in the end it should be

 {'A01':{a:3, b:1, 'B02':{a,2}}

I have this code so far:

d = {'job': {'general_types': 0}}
d['job'] ={}
d['general_types'] ={}
with open("sample.csv", "r") as data1:
    outcome_reader = csv.reader(data1)
    for rows in outcome_reader:
        d['job'].setdefault(rows[0])
        d['general_type'].setdefault(rows[3],0)
        d['general_type'][rows[3]] += 1

Currently however I'm getting a KeyError: 'general_type'

A KeyError is raised whenever you're requesting a key from a dictionary that does not exist.

It looks like you're declaring the key as 'general_types' and then are requesting it by the name 'general_type' . Try this instead:

d['general_types'].setdefault(rows[3],0)
d['general_types'][rows[3]] += 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