如何将python词典合并为文档合并为文档与docx-mailmerge的文档 [英] How do I get a python dictionary into a document merge as kwargs with docx-mailmerge

查看:1080
本文介绍了如何将python词典合并为文档合并为文档与docx-mailmerge的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这本字典

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

然后我使用docx-mailmerge将这些数据合并到word文档中.

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)

但是创建的文档为空.我猜这只适用于kwargs?

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

我只能将合并与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.

我要将字典转换为kwarg(以及如何操作)还是使用字典?

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

谢谢您的帮助!

推荐答案

不确定官方名称是什么,但我称其为爆炸"运算符.

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

document.merge(**mydict)

这会将dict解压缩到函数/方法的关键字参数中.

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

示例:

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


请注意,还有args爆炸:


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

这篇关于如何将python词典合并为文档合并为文档与docx-mailmerge的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆