Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition)

dictionary, python

Solution

To make a `dict` from your `dict`,

subdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)

Problem

I have a python dictionary whose keys are strings and the values are objects. For instance, an object with one string and one int ``` class DictItem: def __init__(self, field1, field2): self.field1 = str(field1) self.field2 = int(field2) ``` and the dictionary: ``` myDict = dict() myDict["sampleKey1"] = DictItem("test1", 1) myDict["sampleKey2"] = DictItem("test2", 2) myDict["sampleKey3"] = DictItem("test3", 3) ``` Which is the best/most efficient way to get the dictionary entries that have the "field2" field >= 2? The idea is creating a "sub-dictionary" (a list would do too) only with the entries in which field2 >= 2 (in the example would be like): ``` { "sampleKey2": { "field1" : "test2", "field2": 2 }, "sampleKey3": { "field1" : "test3", "field2": 3 } } ``` Is there a better way than walking through all the dictionary elements and check for the condition? Maybe using itemgetters, and lambda functions? Thank you! P.S.: I am using Python2.4, just in case it's relevant

Original source