I have a python dictionary whose keys are strings and the values are objects.
For example, an object with one line and one int
class DictItem: def __init__(self, field1, field2): self.field1 = str(field1) self.field2 = int(field2)
and dictionary:
myDict = dict() myDict["sampleKey1"] = DictItem("test1", 1) myDict["sampleKey2"] = DictItem("test2", 2) myDict["sampleKey3"] = DictItem("test3", 3)
What is the best / most efficient way to get dictionary entries that have a field of "field2"> = 2?
The idea is to create a “sub-dictionary” (the list will also do) only with elements in which field2> = 2 (in the example it will):
{ "sampleKey2": { "field1" : "test2", "field2": 2 }, "sampleKey3": { "field1" : "test3", "field2": 3 } }
Is there a better way than to go through all the dictionary elements and check the condition? Maybe using itemgetters and lambda functions?
Thanks!
PS: I use Python2.4, just in case it is relevant
python dictionary
Borrajax
source share