# sparse vector in python?

• Last Update :
• Techknowledgy :
```def convertVector(numbers):
d = {}
for k, c in enumerate(numbers):
if c:
d[k] = c
return d

print convertVector([1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4])
print convertVector([1, 0, 1, 0, 2, 0, 1, 0, 0, 1, 0])
print convertVector([0, 0, 0, 0, 0])```

A one liner using conditional dictionary comprehension:

```def sparseVector(v):
return {
n: val
for n,
val in enumerate(v) if val
}

v1 = [1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4]
v2 = [1, 0, 1, 0, 2, 0, 1, 0, 0, 1, 0]
v3 = [0, 0, 0, 0, 0]

>>>
[sparseVector(v) for v in [v1, v2, v3]]
[{
0: 1,
3: 2,
7: 3,
12: 4
},
{
0: 1,
2: 1,
4: 2,
6: 1,
9: 1
},
{}
]```
```def convertVector(numbers):
dic = {}
for i in range(len(numbers)):
if numbers[i] != 0:
dic[i] = numbers[i]
return dic```

Look at some of the awesome advises people gave you above. One way to do the problem is:

```    def convertVector(numbers):
Value = []
for number, w in enumerate(numbers):
if w != 0:
Value.append((number, w))
return dict(Value)```

Suggestion : 2

Last Updated : 07 Jul, 2021,GATE CS 2021 Syllabus

Examples:

```Input: vector = {
2,
0,
0,
0,
0,
3,
0,
4,
0,
0,
0,
1,
5,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
0,
0,
0,
2,
0,
0,
0,
0,
0,
0,
3,
0,
0,
0,
1,
0,
0,
0,
0,
5
}
Output: {
2,
3,
4,
1,
5,
4,
2,
3,
1,
5
}```

```index: 0 - > value: 2
index: 5 - > value: 3
index: 7 - > value: 4
index: 11 - > value: 1
index: 12 - > value: 5
index: 22 - > value: 4
index: 26 - > value: 2
index: 33 - > value: 3
index: 37 - > value: 1
index: 42 - > value: 5```

```index: 0 - > value: 2
index: 5 - > value: 3
index: 7 - > value: 4
index: 11 - > value: 1
index: 12 - > value: 5
index: 22 - > value: 4
index: 26 - > value: 2
index: 33 - > value: 3
index: 37 - > value: 1
index: 42 - > value: 5```

Suggestion : 3

A simple sparse vector class for passing data to MLlib. Users may alternatively pass SciPy’s {scipy.sparse} data types.,Convert this vector to the new mllib-local representation.,Convert this vector to the new mllib-local representation. This does NOT copy the data; it copies references.,Parse string representation back into the SparseVector.

```>>> a = SparseVector(4, [1, 3], [3.0, 4.0]) >>>
a.dot(a)
25.0
>>>
a.dot(array.array('d', [1., 2., 3., 4.]))
22.0
>>>
b = SparseVector(4, [2], [1.0]) >>>
a.dot(b)
0.0
>>>
a.dot(np.array([
[1, 1],
[2, 2],
[3, 3],
[4, 4]
]))
array([22., 22.]) >>>
a.dot([1., 2., 3.])
Traceback(most recent call last):
...
AssertionError: dimension mismatch >>>
a.dot(np.array([1., 2.]))
Traceback(most recent call last):
...
AssertionError: dimension mismatch >>>
a.dot(DenseVector([1., 2.]))
Traceback(most recent call last):
...
AssertionError: dimension mismatch >>>
a.dot(np.zeros((3, 2)))
Traceback(most recent call last):
...
AssertionError: dimension mismatch```
```>>> a = SparseVector(4, [0, 1], [3., -4.]) >>>
a.norm(1)
7.0
>>>
a.norm(2)
5.0```
```>>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')
SparseVector(4, {
0: 4.0,
1: 5.0
})```
```>>> a = SparseVector(4, [1, 3], [3.0, 4.0]) >>>
a.squared_distance(a)
0.0
>>>
a.squared_distance(array.array('d', [1., 2., 3., 4.]))
11.0
>>>
a.squared_distance(np.array([1., 2., 3., 4.]))
11.0
>>>
b = SparseVector(4, [2], [1.0]) >>>
a.squared_distance(b)
26.0
>>>
b.squared_distance(a)
26.0
>>>
b.squared_distance([1., 2.])
Traceback(most recent call last):
...
AssertionError: dimension mismatch >>>
b.squared_distance(SparseVector(3, [1, ], [1.0, ]))
Traceback(most recent call last):
...
AssertionError: dimension mismatch```

Suggestion : 4

Build a block diagonal sparse matrix from provided matrices.,SciPy 2-D sparse array package for numeric data.,Build a sparse matrix from sparse sub-blocks, Sparse matrices ( scipy.sparse )

`A = csr_array(eye(3))`
```>>>
import numpy as np
>>>
from scipy.sparse
import csr_matrix
>>>
A = csr_matrix([
[1, 2, 0],
[0, 0, 3],
[4, 0, 5]
]) >>>
v = np.array([1, 0, -1]) >>>
A.dot(v)
array([1, -3, -1], dtype = int64)```
```>>> np.dot(A.toarray(), v)
array([1, -3, -1], dtype = int64)```
```>>> from scipy.sparse
import lil_matrix
>>>
from scipy.sparse.linalg
import spsolve
>>>
from numpy.linalg
import solve, norm
>>>
from numpy.random
import rand```
```>>> A = lil_matrix((1000, 1000)) >>>
A[0,: 100] = rand(100) >>>
A[1, 100: 200] = A[0,: 100] >>>
A.setdiag(rand(1000))```
```>>> A = A.tocsr() >>>
b = rand(1000) >>>
x = spsolve(A, b)```

Suggestion : 5

May 18, 2016 , Released: May 18, 2016 , Uploaded May 18, 2016 source

Installation is simply:

`\$ pip install sparse_vector`

Suggestion : 6

LOL, i realized my mistake, i hit submit and it went, but came back wanting the sparse vector, but i realized just now its just a very similar exercise, so i already completed the one before. Thanks for the help though!,which returns the correct results, but in the wrong order, i experimented with sort and sorted but it always messed up, how can i sort the dictionary as it is, without changing the results? seems i always get stuck at the easiest bits, We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge. , Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

Stuck again, this time my problem is getting the dictionary to be sorted in ascending order. Please Advise! the following is what the task says:
"""
A sparse vector is a vector whose entries are almost all zero, like [1, 0, 0, 0, 0, 0, 0, 2, 0]. Storing all those zeros wastes memory and dictionaries are commonly used to keep track of just the nonzero entries. For example, the vector shown earlier can be represented as {0:1, 7:2}, since the vector it is meant to represent has the value 1 at index 0 and the value 2 at index 7. Write a function that converts a dictionary back to its sparese vector representation.

```Examples

>>>
convertDictionary({
0: 1,
3: 2,
7: 3,
12: 4
})[1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4] >>>
convertDictionary({
0: 1,
2: 1,
4: 2,
6: 1,
9: 1
})[1, 0, 1, 0, 2, 0, 1, 0, 0, 1] >>>
convertDictionary({})[]```

I wrote the following:

```def convertVector(numbers):
t = []
c = []
h = len(numbers)
for x in numbers:
if x == 0:
continue
else:
t.append(numbers.index(x) + (h - len(numbers)))
c.append(x)
numbers.pop(numbers.index(x))
return dict(zip(t, c))```

You are not taking dictionary as input, this is the other direction? The dictionary has not order, so that does not matter.

```>>> def print_dictionary(d):
print '[%s]' % (', '.join('%s' % (0
if v not in d
else d[v]) for v in range(min(d), max(d) + 1)))

>>>
print_dictionary({
0: 1,
…```

You are not taking dictionary as input, this is the other direction? The dictionary has not order, so that does not matter.

```>>> def print_dictionary(d):
print '[%s]' % (', '.join('%s' % (0
if v not in d
else d[v]) for v in range(min(d), max(d) + 1)))

>>>
print_dictionary({
0: 1,
2: 1,
4: 2,
6: 1,
9: 1
})[1, 0, 1, 0, 2, 0, 1, 0, 0, 1] >>>```