Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 849
BorrajaX Avatar asked Mar 08 '10 17:03

BorrajaX


2 Answers

To make a dict from your dict,

subdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)
like image 124
Alex Martelli Avatar answered Sep 20 '22 11:09

Alex Martelli


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

Documentation:

list-comprehensions, iteritems()

like image 37
mechanical_meat Avatar answered Sep 18 '22 11:09

mechanical_meat