BPy set keyframe by active object only?
Use the API method rather than an operator.

Making the assumption that if all selected objects are being keyframed, you are using an operator to set keyframes.

Much easier to use keyframe_insert(data_path, index=-1, frame=bpy.context.scene.frame)

Index default is -1 for all components (eg x, y and z of a location) or 0, 1, 2, 3, (location.x ==&gt; location[0]) 

The method returns True if the keyframe has been successfully added.

An example of adding all location keyframe to the active object. Set the location, then insert the keyframe(s). 

import bpy
ob = bpy.context.object
ob.location = (1, 2, 4)
# add this as keyframe at frame 10
ob.keyframe_insert("location", frame=10)


Take z up to 19 at frame 100

ob.location.z = 19
ob.keyframe_insert('location', index=2, frame=100)