Custom bone weights lost when switching to object mode
One way is to set up a dictionary with key groupname and a list of vertex indices and add them in object mode using vertex_group.add(..)

import bpy
context = bpy.context
ob = context.object

dic = {}
for g in ob.vertex_groups:
    dic[g.name] = []

for vertex in ob.data.vertices:
    for gr in vertex.groups:
        dic[ob.vertex_groups[gr.group].name].append(vertex.index)

# has to be in object mode for vertex_group.add
bpy.ops.object.mode_set()
w = 1.0
for vgname, verts in dic.items():
    #print(vgname)
    ob.vertex_groups[vgname].add(verts, w, 'REPLACE')