[英]Creating dictionary from CSV file,
For the following CSV File: 对于以下CSV文件:
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. 字典没有append
方法。 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. 当一个不存在的setdefault
缺省值设置为{}
时, setdefault
设置一个新键,并且更新方法会使用新值更新该键处的字典。
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]} )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.