DEV Community

Discussion on: Daily Challenge #204 - Partial Keys

Collapse
 
vidit1999 profile image
Vidit Sarkar

Python approach

class ObjectSpecial:
    def __init__(self, dictLike):
        # sort the dictionary with respect to keys
        # so now keys will be sorted in alphabetical order
        self.dictLike = dict(sorted(dictLike.items()))


    def __getattr__(self, s):
        # if any key starts with s then return the corresponding value
        # if key not found return 0
        for k, v in self.dictLike.items():
            if(k.startswith(str(s))):
                return v
        return 0

partialKey = lambda dictLike : ObjectSpecial(dictLike)

d = {'abcd' : 1,'abbd' : 2, 'abdd' : 3}
o = partialKey(d)

print(o.a) # output : 2
print(o.ab) # output : 2
print(o.abcd) # output : 1
print(o.abd) # output : 3
print(o.k) # output : 0 as key not present
print(o.ac) # output : 0 as key not present