问题
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