From 8eaad5c3e83d2f2156d1d550a898db07f4c55740 Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Sun, 9 Jun 2024 13:56:12 -0700 Subject: [PATCH] Added to_dict method to SparseVector --- pgvector/utils/sparsevec.py | 3 +++ tests/test_sparse_vector.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/pgvector/utils/sparsevec.py b/pgvector/utils/sparsevec.py index c4aa4f1..f33e496 100644 --- a/pgvector/utils/sparsevec.py +++ b/pgvector/utils/sparsevec.py @@ -49,6 +49,9 @@ def from_dense(cls, value): def dim(self): return self._dim + def to_dict(self): + return {i: v for i, v in zip(self._indices, self._values)} + def to_list(self): vec = [0.0] * self._dim for i, v in zip(self._indices, self._values): diff --git a/tests/test_sparse_vector.py b/tests/test_sparse_vector.py index c799fa3..c1258dc 100644 --- a/tests/test_sparse_vector.py +++ b/tests/test_sparse_vector.py @@ -26,3 +26,6 @@ def test_repr(self): def test_dim(self): assert SparseVector.from_dense([1, 0, 2, 0, 3, 0]).dim() == 6 + + def test_to_dict(self): + assert SparseVector.from_dense([1, 0, 2, 0, 3, 0]).to_dict() == {0: 1, 2: 2, 4: 3}