Skip to content Skip to sidebar Skip to footer

How To Remove Values From Dictionary That Are Not Numbers In Python?

I have a dictionary of this type d={'Key':[name,value1,value2]} I need only numbers in my value's list. How can I remove name ? Thak you!

Solution 1:

import numbers

for key, values in d.iteritems():
   d[key] = [x for x in values ifisinstance(x, numbers.Number)]

The numbers package is available since 2.6. Otherwise you need to check manually for any numerical type (int, float, long, complex)

iteritems() has been removed and is now identical to items() in 3.x

Solution 2:

If name is always at the start of the list, the simply d['Key'][1:] will suffice. Otherwise, you can use the following:

[i for i in d['Key'] if i.isdigit()]

Of course, I'm assuming that all of the items in d['Key'] are strings. Otherwise you cannot use isdigit().

Solution 3:

In [1]: d = {'k1': [1,2,3,'a','b','c'], 'k2': ['e',4.3,'f',5.2]}
In [2]: for k,v in d.iteritems():
   ...:     #This will keep only integers, but will fail on the floats since isdigit() return False on non-integers 
   ...:     d[k] = filter(lambda e: str(e).isdigit(), v)

   ...:     #On the other hand, This will be a generic solution for any numeric type
   ...:     d[k] = filter(lambda e: isinstance(e, numbers.Number), v)
   ...:
In [3]: d
Out[3]: {'k1': [1, 2, 3], 'k2': [4.3, 5.2]}

Post a Comment for "How To Remove Values From Dictionary That Are Not Numbers In Python?"