如何获得嵌套字典,其中键和子键的顺序正好与csv文件中的顺序相同?
我试过
import csv
from collections import OrderedDict
filename = "test.csv"
aDict = OrderedDict()
with open(filename, 'r') as f:
csvReader = csv.DictReader(f)
for row in csvReader:
key = row.pop("key")
aDict[key] = row
test.csv看起来像
key,number,letter
eins,1,a
zwei,2,b
drei,3,c
但子词典没有排序(行号和数字都有变化)。那么如何以有序的方式填充aDict[key]
?
答案 0 :(得分:3)
您必须自己从class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if request.user in permited user:
obj.save()
else:
raise forms.ValidationError("you can't do that.")
返回的行(而不是使用csv.reader
)构建词典和子词典。
幸运的是,这很容易:
csv.DictReader
输出:
import csv
from collections import OrderedDict
filename = 'test.csv'
aDict = OrderedDict()
with open(filename, 'rb') as f:
csvReader = csv.reader(f)
fields = next(csvReader)
for row in csvReader:
temp = OrderedDict(zip(fields, row))
key = temp.pop("key")
aDict[key] = temp
import json # just to create output
print(json.dumps(aDict, indent=4))
答案 1 :(得分:2)
这是一种方式:
import csv
from collections import OrderedDict
filename = "test.csv"
aDict = OrderedDict()
with open(filename, 'r') as f:
order = next(csv.reader(f))[1:]
f.seek(0)
csvReader = csv.DictReader(f)
for row in csvReader:
key = row.pop("key")
aDict[key] = OrderedDict((k, row[k]) for k in order)
答案 2 :(得分:0)
csv.DictReader
将行加载到常规dict
而不是有序行。您必须手动将csv读入OrderedDict
才能获得所需的订单:
from collections import OrderedDict
filename = "test.csv"
dictRows = []
with open(filename, 'r') as f:
rows = (line.strip().split(',') for line in f)
# read column names from first row
columns = rows.next()
for row in rows:
dictRows.append(OrderedDict(zip(columns, row)))
答案 3 :(得分:0)
您可以利用现有的csv.DictReader
类,但可以更改它返回的行。为此,请将以下类添加到脚本的开头:
class OrderedDictReader(csv.DictReader):
def next(self):
# Get a row using csv.DictReader
row = csv.DictReader.next(self)
# Create a new row using OrderedDict
new_row = OrderedDict(((k, row[k]) for k in self.fieldnames))
return new_row
然后,使用此类代替csv.DictReader
:
csvReader = OrderedDictReader(f)
其余代码保持不变。