You can find the group dynamically by getting the name of the layer's parent in the layer tree:
# reference to the project
p = QgsProject.instance()
# names of layers to remove from legend
layers_to_remove = ['layer1', 'layer2']
# the layer tree
root = p.layerTreeRoot()
# layout manager
manager = p.layoutManager()
# first layout (can also use manager.layoutByName() )
layout = manager.layouts()[0]
# get legend
legend = [i for i in layout.items() if isinstance(i, QgsLayoutItemLegend)][0]
# disable auto-update
legend.setAutoUpdateModel(False)
# legend model
model = legend.model()
# the root legend group
root_group = model.rootGroup()
# loop through layer names
for layer_name in layers_to_remove:
# find layer in project
layer = p.mapLayersByName(layer_name)[0]
# get layer tree layer instance of layer
layertreelayer = root.findLayer(layer.id())
# get the parent of the layer tree layer (layer tree root, or group)
parent = layertreelayer.parent()
# if the parent is a group and has a name, find it and remove the layer
if isinstance(parent, QgsLayerTreeGroup) and parent.name():
group = root_group.findGroup(parent.name())
group.removeLayer(layer)
# remove layers that are not in a group
else:
root_group.removeLayer(layer)
# update legend
legend.adjustBoxSize()
layout.refresh()
Note: there will need to be some extra logic (e.g. recursion) added to deal with sub-groups.