Search code examples
pythonnumpy

TypeError: loop of ufunc does not support argument 0 of type dict which has no callable sqrt method


I am stuck with an error:

psi_out_norm.append(np.sqrt(sorted_probs))
TypeError: loop of ufunc does not support argument 0 of type dict which has no callable sqrt method

Not sure how to resolve this error. Below is the code i am working on:

import numpy as np
num_qubits = 2
sorted_probs = {'00': 0.1826131640519985, '01': 0.3015290853531944, '10': 0.3171301575715357, '11': 0.1987275930232714}
all_possible_keys = [format(i, f'0{num_qubits}b') for i in range(2**num_qubits)]

psi_out_norm = []
for key in all_possible_keys:  
    count = sorted_probs.get(key, 0) # use 0 if the key is missing
    psi_out_norm.append(np.sqrt(sorted_probs))

It would be great help if someone can help me in this error.


Solution

  • You are trying to run np.sqrt on a dictionary. This is what causes the TypeError. You can replace sorted_probs with count:

    import numpy as np
    num_qubits = 2
    sorted_probs = {'00': 0.1826131640519985, '01': 0.3015290853531944, '10': 0.3171301575715357, '11': 0.1987275930232714}
    all_possible_keys = [format(i, f'0{num_qubits}b') for i in range(2**num_qubits)]
    
    psi_out_norm = []
    for key in all_possible_keys:  
        count = sorted_probs.get(key, 0) # use 0 is the key is missing
        psi_out_norm.append(np.sqrt(count))