Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to filter a dictionary in Python [duplicate]

I have a dictionary of string keys and float values.

 mydict = {}
 mydict["joe"] = 20
 mydict["bill"] = 20.232
 mydict["tom"] = 0.0

I want to filter the dictionary to only include pairs that have a value greater than zero.

In C#, I would do something like this:

   dict = dict.Where(r=>r.Value > 0);

What is the equivalent code in Python?

like image 775
leora Avatar asked Dec 08 '11 01:12

leora


People also ask

How do you filter a dictionary in python?

Filter a Dictionary by values in Python using filter() filter() function iterates above all the elements in passed dict and filter elements based on condition passed as callback.

How do I remove duplicates from a dictionary list?

The strategy is to convert the list of dictionaries to a list of tuples where the tuples contain the items of the dictionary. Since the tuples can be hashed, you can remove duplicates using set (using a set comprehension here, older python alternative would be set(tuple(d.

Is duplicates allowed in dictionary python?

Practical Data Science using PythonPython dictionary doesn't allow key to be repeated.


1 Answers

d = dict((k, v) for k, v in d.iteritems() if v > 0)

In Python 2.7 and up, there's nicer syntax for this:

d = {k: v for k, v in d.items() if v > 0}

Note that this is not strictly a filter because it does create a new dictionary.

like image 161
kindall Avatar answered Oct 20 '22 04:10

kindall