0

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

tvdsluijs
  • 127
  • 11

2 Answers2

2

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
Stephen C
  • 1,966
  • 1
  • 16
  • 30
0

Use the merge_pages method when passing a dict to a Mailmerge object: document.merge_pages([mydict])

# keys = your mergefield names, values = what you want to insert into each mergefield
mydict = {'name': 'Theo', 'age': '39', 'gender': 'male', 'eyecolor': 'brown'}

template = "myworddoc.docx"
newdoc = "mergeddoc.docx"
document = MailMerge(template)

print([i for i in document.get_merge_fields()] # Verify your merge fields exist
document.merge_pages([mydict])
document.write(newdoc)
document.close()
j_rothmans
  • 31
  • 5