在动态生成的Python字典中访问值
我有一个很大的XML文件一直在折磨我。我已经设法解决了其设计中的许多缺陷,并希望将其转移到python字典中,以便稍后写入SQL等。同时,我可以使用该字典完成我的任务 以下是我的代码中存在的问题:在动态生成的Python字典中访问值,python,dictionary,nested,Python,Dictionary,Nested,我有一个很大的XML文件一直在折磨我。我已经设法解决了其设计中的许多缺陷,并希望将其转移到python字典中,以便稍后写入SQL等。同时,我可以使用该字典完成我的任务 以下是我的代码中存在的问题: import os, csv from collections import Counter from pprint import pprint dd = {} x=0 with open('transactions.csv', 'r') as f: reader = csv.DictRea
import os, csv
from collections import Counter
from pprint import pprint
dd = {}
x=0
with open('transactions.csv', 'r') as f:
reader = csv.DictReader(f)
h = (reader.fieldnames)
for row in reader:
x+=1
for i in h:
dd[x] = {'date':row['Date'],
'amount':row[' Amount'],
'type':row[' Type'],
'note':row[' Description']
}
我的想法是,我正在阅读文件(在本例中是一个练习文件)并将其输入字典。有一把钥匙,上面有一个条目。我可以枚举它并将其用作索引,也可以手动计数。我还可以为dd[x]使用唯一字段。但无论我做什么,我都无法单独访问字典中的值
例如,最好执行以下操作:
print (dd[25]['date'])
我每次都觉得冷。我想我可以访问条目25(dd[25])并获得日期(dd[25]['date'])
我在嵌套字典中找到的所有示例都是手动构造的,并没有解决我似乎无法解决的问题
请告知。非常感谢 对于记录,您不需要重新创建字典,行已经是dicts:
for row in reader:
x+=1
for i in h:
dd[x] = {'date':row['Date'],
'amount':row[' Amount'],
'type':row[' Type'],
'note':row[' Description']
......
}
for key in dd[x].keys(): ## iterate through keys
print d[x][key]
import csv
dd = {}
with open('mycsv.csv', 'r') as f:
reader = csv.DictReader(f)
h = next(reader)
for x, row in enumerate(reader, 1):
dd[x] = row
print(dd)
输出
{1: {'Date': '4/30/16', 'Amount': '11.23', 'Type': '1', 'Description': 'Something 1'}, 2: {'Date': '4/30/16', 'Amount': '10.23', 'Type': '2', 'Description': 'Something 2'}, 3: {'Date': '4/30/16', 'Amount': '9.23', 'Type': '3', 'Description': 'Something 3'}, 4: {'Date': '4/30/16', 'Amount': '8.23', 'Type': '4', 'Description': 'Something 4'}}
同样值得注意的是,使用列表似乎是合适的,因为它们通常用于数字连续索引数据这些与XML有什么关系?我想你的意思是“CSV”。