1
0

More than 3 years have passed since last update.

大小文字区別しない辞書機能を作ってみました

Posted at

※特殊メソッドをオーバーライドで実現します。

dictex01.py
class PcInformation:
    def __init__(self):
        self.pc_dict = {}

    def __getitem__(self, key):
        return self.pc_dict.get(key.upper(), '---未設定---')  # キーは大文字で統一

    def __setitem__(self, key, value):
        self.pc_dict[key.upper()] = value  # キーは大文字で統一

    def __delitem__(self, key):
        del self.pc_dict[key.upper()]  # キーは大文字で統一

    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'  # 大小文字区別しないことにしているから、更新できる
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'])  # 大小文字区別しないことにしているから、取得できる
print(pc_inf['wpc999'])  # wpc999は辞書にない
del pc_inf['WpC_010']  # 削除

print('端末数:{}'.format(len(pc_inf)))
print('端末一覧:')
for i, item in enumerate(pc_inf.pc_dict.items()):
    print('{:>5})  PC Name: {:<12}    IP: {}'.format(str(i + 1), item[0], item[1]))

実行結果:
192.168.1.11
---未設定---
端末数:3
端末一覧:
    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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0