[類別篇] 設計不具有大小寫鍵值的 dict - tsungjung411/python-study GitHub Wiki

基本版

class IgnoreCaseDict(dict):

    def __setitem__(self, key, value):
        if type(key) == str:
            key = key.lower()
        super().__setitem__(key, value)

    def __getitem__(self, key):
        if type(key) == str:
            key = key.lower()
        return super().__getitem__(key)
        
d = IgnoreCaseDict()
d['NAME'] = 'tj'
d['full_name'] = 'tj_tsai'
d[None] = 'none key'

print('NAme:', d['NAme'])
print('name:', d['name'])
print('FULL_NAME:', d['full_name'])
print('full_NAME:', d['full_NAME'])

執行結果:

NAme: tj
name: tj
FULL_NAME: tj_tsai
full_NAME: tj_tsai

完整版

class CaseInsensitiveDict(dict):
    def __init__(self, default_dict = None):
        if default_dict != None:
            for key, value in default_dict.items():
                if type(key) == str:
                    key = key.lower()

                if isinstance(value, dict):
                    value = __convert_key_to_lower(value)

                self[key] = value
            # end-of-for
        # end-of-if
    
    @staticmethod
    def __convert_key_to_lower(old_dict):
        new_dict = dict()
        for key, value in old_dict.items():
            if type(key) == str:
                key = key.lower()
            
            if isinstance(value, dict):
                value = __convert_key_to_lower(value)
            
            new_dict[key] = value
        # end-of-for
        return new_dict
    
    def __setitem__(self, key, value):
        if type(key) == str:
            key = key.lower()
        if isinstance(value, dict):
            value = CaseInsensitiveDict.__convert_key_to_lower(value)
        super().__setitem__(key, value)

    def __getitem__(self, key):
        if type(key) == str:
            key = key.lower()
        return super().__getitem__(key)
        
d = CaseInsensitiveDict({'job': 'Engineer'})
d['FULL_name'] = 'tj_tsai'
d['Profile'] = {
    'Age': 25,
    'GENDER': 'Male'
}
d[None] = 'none key'

print('FULL_NAME:', d['full_name'])
print('full_NAME:', d['full_NAME'])
print('PROfile:', d['PROfile'])
print(d)

執行結果:

FULL_NAME: tj_tsai
full_NAME: tj_tsai
PROfile: {'age': 25, 'gender': 'Male'}
{'job': 'Engineer', 'full_name': 'tj_tsai', 'profile': {'age': 25, 'gender': 'Male'}, None: 'none key'}