Accessing Python dict values with the key start characters

后端 未结 7 1539
南笙
南笙 2020-12-28 13:56

I was wondering: would it be possible to access dict values with uncomplete keys (as long as there are not more than one entry for a given string)? For example:



        
7条回答
  •  死守一世寂寞
    2020-12-28 14:09

    not the best solution, can be improved (overide getitem)

    class mydict(dict):
        def __getitem__(self, value):
            keys = [k for k in self.keys() if value in k]
            key = keys[0] if keys else None
            return self.get(key)
    
    
    my_dict = mydict({'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'})
    print(my_dict['Date'])# returns 15th july
    

提交回复
热议问题