Reputation: 1
I have a list with float values, for example x = [0.0, 0.5, 0.0 , 0.8]
.
I created a dictionary that stores the indices and list values as keys
dict = { 'inds' : [0,1,2,3] , 'vals' : [0.0, 0.5, 0.0, 0.8]}
I need to filter the dictionary in such a way that returns all non-zero vector values and return that dictionary such that:
dict['inds'] = [1,3]
dict['vals'] = [0.5, 0.8]
I have tried several different comprehension techniques but can't seem to find one to evaluate the float objects inside the 'vals' list
x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0]
d = {'inds' : [], 'vals' :[]}
c = {}
for i in range(len(x)):
c[i] = x[i]
d['inds'] = list(c.keys())
d['vals'] = list(c.values())
Upvotes: 0
Views: 16
Reputation: 49920
Like this:
x = [0.0, 0.5, 0.0 , 0.8]
c = {k:v for k,v in enumerate(x) if v != 0.0}
d = {'inds':list(c.keys()), 'vals':list(c.values())}
Upvotes: 2