python合并多个docx_我如何将python字典合并为文档合并为docx-mailmerge的文档

So I've got this dictionary

mydict = {'name': 'Theo', 'age': '39', 'gender': 'male', 'eyecolor': 'brown'}

and I use docx-mailmerge to merge this data into a word document.

template = "myworddoc.docx"

newdoc = "mergeddoc.docx"

document = MailMerge(template)

document.merge(mydict)

document.write(newdoc)

But the document created is empty. I guess it only works with kwargs??

Can I only use the merge with kwargs so

document.merge(name='Theo', age='39', gender='male', eyecolor='brown')

I really like to use a dictionary to merge the data.

Do I transform the dict to kwarg (and how do I do this) or do I use the dict?

Thank you for helping out!!

解决方案

Not sure what the official name is, but I call it the "explode" operator.

document.merge(**mydict)

This unpacks the dict into the function's/method's keyword arguments.

Example:

def foo_kwargs(a=1, b=2, c=3):

print(f'a={a} b={b} c={c}')

my_dict = {'a': 100, 'b': 200, 'c': 300}

foo_kwargs(**my_dict)

# Prints a=100 b=200 c=300

Note that there is also the args explode:

mylist = [1,2,3,4]

def foo_args(a, b, c, d):

print(a, b, c ,d)

foo_args(*mylist)

# Prints 1 2 3 4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值