partial match dictionary key(of tuples) in python

后端 未结 4 1350
长发绾君心
长发绾君心 2020-12-09 13:00

I have a dictionary that maps 3tuple to 3tuple where key-tuples have some element in common

dict= { (a,b,c):(1,2,3),
        (a,b,d):tuple1,
        (a,e,b):         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 13:13

    @AshwiniChaudhary's solution can be trivially adapted for an object-oriented solution. You can subclass dict and add a method:

    class tup_dict(dict):
        def getitems_fromtup(self, key):
            for k, v in self.items():
                if all(k1 == k2 or k2 is None for k1, k2 in zip(k, key)):
                    yield v
    
    d = tup_dict({("foo", 4 , "q"): 9,
                  ("foo", 4 , "r"): 8,
                  ("foo", 8 , "s"): 7,
                  ("bar", 15, "t"): 6,
                  ("bar", 16, "u"): 5,
                  ("baz", 23, "v"): 4})
    
    res = list(d.getitems_fromtup(("foo", 4, None)))  # [9, 8]
    

提交回复
热议问题