# Converting a dictionary to a statevector in Qiskit

Suppose we have a dictionary of computational basis states and their amplitudes:

{'01':0.5, '10':0.5, '11':0.5, '00':0.5}

How do I convert this (or any arbitrary dictionary) into a Statevector object? In this case the statevector should be is

$$| \psi \rangle = \frac{|00 \rangle + |01 \rangle + |10 \rangle + |11 \rangle}{2}$$

I don't think there a built-in functionality for this in Qiskit. However, it is easy to implement. The below code snippet shows how to do that:

from qiskit.quantum_info import Statevector
import numpy as np

_state = {'01':0.5, '10':0.5, '11':0.5, '00':0.5}

# Convert dictionary into array:
num_qubits = len(next(iter(_state)))
data = np.zeros(2 ** num_qubits)

for key in _state:
data[int(key, 2)] = _state[key]

psi = Statevector(data)

# Check:
psi.draw('latex')


Note that, it is not a production-quality code. For example, there is an implicit assumption that all the dictionary keys have the same length.

Statevector can be initialized using a list of amplitudes as an argument, so you need to convert the dictionary into a list, with the bit string keys converted into integer indices (using little endian notation) and the values of the list at those indices set to the corresponding values from the dictionary.