gpt4 book ai didi

python - 我该如何放置字典 {key : value} in it's designated key in a dictionary so that it is {key: {key: value}} after counting value

转载 作者:行者123 更新时间:2023-12-01 03:50:57 25 4
gpt4 key购买 nike

我有一个 csv 文件,我正在尝试对 row[3] 进行计数,然后将其与 row[0] 连接

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

所以最后应该是

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

到目前为止我有这个代码:

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

目前我收到了 KeyError: 'general_type'

最佳答案

每当您从不存在的字典请求 key 时,都会引发 KeyError

看起来您将 key 声明为'general_types',然后通过名称'general_type'请求它。试试这个:

d['general_types'].setdefault(rows[3],0)
d['general_types'][rows[3]] += 1

关于python - 我该如何放置字典 {key : value} in it's designated key in a dictionary so that it is {key: {key: value}} after counting value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38269203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com