gpt4 book ai didi

python - 将字典数组转换为具有潜在不匹配字段名的二维数组

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:53 27 4
gpt4 key购买 nike

我正在使用 csv.Dictreader 读取 csv 文件,因为通过字段名访问项目非常方便,但是 csv.Dictwriter 类非常挑剔它如何处理字段名。我收到很多 "dict contains fields not in fieldnames" 异常,当我特别不希望 dict 包含我提供的所有字段名时。我还希望能够提供一个字段名列表,其中的键可能不会出现在字典列表的每一行中。

因此,我创建了一种将字典列表转换为二维数组的方法,我可以将其与 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

示例输入/输出:

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

谢谢你的时间

最佳答案

这会产生您的输出:

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)

结果:

[['one', 'three', 'ten'], ['bob', 'cat', ''], ['john', '', 'dog']]

关于python - 将字典数组转换为具有潜在不匹配字段名的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901604/

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