How do I get a python dictionary into a document merge as kwargs with docx-mailmerge

痞子三分冷 提交于 2019-12-25 01:06:27

问题


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!!


回答1:


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


来源:https://stackoverflow.com/questions/53092062/how-do-i-get-a-python-dictionary-into-a-document-merge-as-kwargs-with-docx-mailm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!