# Modifying measurements in a Qiskit circuit

Assume my function Qiskit receives a certain circuit as an input. How do I check if this circuit already has some measurements appended to it? If so, how can I modify them? For example, if there are measurements on certain qubits, I would like to remove those in order to add some more gates, and then add the measurement of all qubits.

The easiest way to do this is probably by converting the circuit to a DAGCircuit, which can be done using the method from qiskit.converters import circuit_to_dag. From the DAG you can get properties, such as any measurement operations, by using the function my_dag.named_nodes('measurement'). DAGNode objects are returned which will tell you the properties of the measurement. You can then remove nodes using my_dag.remove_op_node(a_measurement_node), it is preferable to remove and add nodes than to modify inplace. Following this you could convert the DAGCircuit back to a QuantumCircuit using from qiskit.converters import dag_to_circuit and then append any measurement operations as desired.

• Wow, that's quite involved but will hopefully work :) Why can't I just copy the gates one by one to another circuit, until I reach the measurement? May 25, 2020 at 20:24
• That would also work, but it would mean creating a new circuit, but if you are fine with doing that it should work May 26, 2020 at 10:34
• Could you explain how exactly I should do it this way? May 26, 2020 at 12:09
• You could iterate over QuantumCircuit.data() which returns a list like object of (instruction, qargs, cargs). You should then be able to do new_circuit.append(instruction, qargs,cargs) May 26, 2020 at 14:07

Since the last answer, now there is an easier solution:

Get an ordered dictionary of the operators in circuit and check if 'measure' is part of it:

ops = circuit.count_ops() # ordered dictionary of operators and their count
if 'measure' in ops.keys(): # iterate over the keys
# do something, e.g. remove all measurements
circuit.remove_final_measurements()
else:
print('no measurements found')


Then you can add any gates you want and measure again using circuit.measure_all()