Joe*_*ult 4 python csv dictionary
我习惯于csv.Dictreader
读取 csv 文件,因为通过字段名访问项目非常方便,但是该类csv.Dictwriter
对于如何处理字段名非常挑剔。"dict contains fields not in fieldnames"
当我特别不希望字典包含我提供的所有字段名时,我遇到了很多异常。我还希望能够提供字段名列表,其中的键可能不会出现在字典列表的每一行中。
因此,我创建了一种将字典列表转换为可以与该csv.writer.writerow
函数一起使用的二维数组的方法。
问题:
我想知道我的方法是好是坏还是丑陋。有没有更好/更Pythonic的方法将具有任意字段名的字典列表转换为二维数组?我错过了一些明显的东西吗csv.DictWriter
?
代码:
它的作用是:
输出将跳过您未提供的字段名称,但如果您提供的字段名称未出现在每个(或任何)行中,但仍将其包含在顶部的标题中,则输出也会仅放置一个空格。 csv 文件。
def csvdict_to_array(dictlist, fieldnames):
# Start with header row
csv_array = [fieldnames]
for row in dictlist:
csv_array.append(dictlist_row_to_list(row, fieldnames))
return csv_array
def dictlist_row_to_list(dictlist_row, fieldnames):
csv_row = []
for field in fieldnames:
if field not in dictlist_row:
csv_row.append('')
else:
csv_row.append(dictlist_row[field])
return csv_row
Run Code Online (Sandbox Code Playgroud)
输入/输出示例:
fieldnames = ["one", "three", "ten"]
dictlist = [{"one": "bob", "two": "bill", "three":"cat"},
{"one": "john", "two": "jack", "ten":"dog"}]
Output:
one,three,ten
bob,cat,
john,,dog
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间
这会产生你的输出:
fieldnames = ["one", "three", "ten"]
dictlist = [{"one": "bob", "two": "bill", "three":"cat"},
{"one": "john", "two": "jack", "ten":"dog"}]
res = [[item.get(key, '') for key in fieldnames] for item in dictlist]
res.insert(0, fieldnames)
print(res)
Run Code Online (Sandbox Code Playgroud)
结果:
[['one', 'three', 'ten'], ['bob', 'cat', ''], ['john', '', 'dog']]
Run Code Online (Sandbox Code Playgroud)