python用字典编写购物程序_在Python中使用DictWriter来编写字典键的子集

1586010002-jmsa.png

I wrote a function that serializes a list of dictionaries as a CSV file using the CSV module. I sometimes want to write out to a file only a subset of each dictionary's keys however. I use the following code:

def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',

lineterminator='\n'):

out_f = open(filename, 'w')

# Write out header

header = delimiter.join(fieldnames) + lineterminator

out_f.write(header)

# Write out dictionary

data = csv.DictWriter(out_f, fieldnames,

delimiter=delimiter,

lineterminator=lineterminator)

data.writerows(dictrows)

out_f.close()

If I pass in "fieldnames" a subset of the keys that each dictionary has, I get the error:

"dict contains fields not in fieldnames"

How can I make it so that DictRows will write just a subset of the fields I specify to CSV, ignoring those fields that are in the dictionary but not in fieldnames?

thanks.

解决方案

Simplest and most direct approach is to pass extrasaction='ignore' when you initialize your DictWriter instance, as documented here:

If the dictionary passed to the

writerow() method contains a key not

found in fieldnames, the optional

extrasaction parameter indicates what

action to take. If it is set to

'raise' a ValueError is raised. If it

is set to 'ignore', extra values in

the dictionary are ignored.

It also works on writerows, which, internally, just calls writerow repeatedly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值