dictex01.py
class PcInformation:
def __init__(self):
self.pc_dict = {}
def __getitem__(self, key):
return self.pc_dict.get(key.upper(), '---Not set---') #Keys are unified in uppercase
def __setitem__(self, key, value):
self.pc_dict[key.upper()] = value #Keys are unified in uppercase
def __delitem__(self, key):
del self.pc_dict[key.upper()] #Keys are unified in uppercase
def __len__(self):
return len(self.pc_dict)
pc_inf = PcInformation()
pc_inf['wpc001'] = '192.168.1.33'
pc_inf['Wpc001'] = '192.168.1.39' #I'm not case-sensitive, so I can update it
pc_inf['WPC010'] = '192.168.1.11'
pc_inf['wpc022'] = '192.168.1.22'
pc_inf['WPC_010'] = '192.168.1.100'
print(pc_inf['wpc010']) #You can get it because it is not case-sensitive
print(pc_inf['wpc999']) #wpc999 is not in the dictionary
del pc_inf['WpC_010'] #Delete
print('Number of terminals:{}'.format(len(pc_inf)))
print('List of terminals:')
for i, item in enumerate(pc_inf.pc_dict.items()):
print('{:>5}) PC Name: {:<12} IP: {}'.format(str(i + 1), item[0], item[1]))
Execution result: 192.168.1.11 --- Not set --- Number of terminals: 3 List of terminals: 1) PC Name: WPC010 IP: 192.168.1.11 2) PC Name: WPC022 IP: 192.168.1.22 3) PC Name: WPC001 IP: 192.168.1.39
Recommended Posts