Python type error: unbound method dict.keys() needs an argument

2.3k Views Asked by At

I am trying to access the keys in my results_dict dictionary with an if statment in my _run method. Specifically I get the TypeError: unbound method dict.keys() needs an argument error on the if (gate.key) in results_dict.keys(): line. I tried just running print(results_dict.keys()) and I get the same TypeError: unbound method dict.keys() needs an argument error I am not sure why I am getting this error.

import cirq
from typing import Dict
from collections import defaultdict
from cirq.sim.simulator import SimulatesSamples
from cirq import ops, protocols
from cirq.study.resolver import ParamResolver
from cirq.circuits.circuit import AbstractCircuit
import numpy as np

def _run(
        circuit: 'AbstractCircuit',
        param_resolver: 'ParamResolver',
        repetitions: int,
    ) -> Dict[str, np.ndarray]:

        results_dict = Dict[str, Dict[str, np.ndarray]]
        values_dict: Dict[cirq.Qid,  int] = defaultdict(int)
        param_resolver = param_resolver or ParamResolver({})
        resolved_circuit = protocols.resolve_parameters(circuit, param_resolver)

        for moment in resolved_circuit:
            for op in moment:
                gate = op.gate

                if isinstance(gate, ops.XPowGate) and gate.exponent == 1:
                    values_dict[op.qubits[0]] = 1 - values_dict[op.qubits[0]]

                elif isinstance(gate, ops.MeasurementGate):
                    qubits_in_order = op.qubits
                    if (gate.key) in results_dict.keys():
                        shape = len(qubits_in_order)
                        current_array = results_dict[gate.key]
1

There are 1 best solutions below

0
On

You didn't create a dict object; you just defined an alias for a particular type hint. Instead, use

results_dict: dict[str, dict[str, np.ndarray]] = {}

(typing.Dict has been deprecated since Python 3.9 in favor of dict itself.)