PythonはDictデータの方法を読んで、keyがdictにいない問題を解決して、get()関数、setdefault()関数

2341 ワード

Pythonは辞書を読んだり書いたりして、KeyがDictの中にいなければ、Key Errorを投げ出すことになります.異常処理をしていなければ、プログラムは切れてしまいます.普段自分で書いて遊んでいるプログラムは、大丈夫です.直してから走り直しましょう.しかし、会社では、1つのプログラムが何日か走るかもしれません.このような小さなバグが切れたので、もう一度走る必要があります.仕事の効率に非常に影響します.だから、辞書を読むときは、必ずKey not in Dictの中の状況を考慮して、異常処理を選択することができます.
 temp = {'a':1,'b':1,'c':1}
 h = ['a','e','c','b']
 for index in h:
      print temp[index]

実行結果:
Traceback (most recent call last):   File "test.py", line 5, in     print temp[index] KeyError: 'e'
例外処理を選択できます.
 temp = {'a':1,'b':1,'c':1}
 h = ['a','e','c','b']
 for index in h:
      try:
           print temp[index]
      except KeyError:
           print "has no key"

    

実行結果:
1 has no key 1 1
もちろん異常処理が面倒なのでget関数で辞書を読み取ることができます
dict.get(key, default=None)
パラメータ
key--辞書で検索するキーです.
「default」--キーが存在しない場合のデフォルト値です.
戻り値
このメソッドは、指定されたキーの値を返します.キーが使用できない場合は、デフォルト値Noneを返します.
Python辞書(Dictionary)setdefault()関数はget()メソッドと同様で、キーが既に辞書に存在しない場合はキーを追加し、値をデフォルト値に設定します.
dict.setdefault(key, default=None)
  
  • key--検索されたキー値.
  • default--キーが存在しない場合に設定されるデフォルトのキー値.

  • 次の例では、setdefault()関数の使用方法を示します.
    dict = {'Name': 'Zara', 'Age': 7}
    
    print "Value : %s" %  dict.setdefault('Age', None)
    print "Value : %s" %  dict.setdefault('Sex', None)
    Value : 7
    Value : None
    girls =['alice','bernice','clarice']
    letterGirls ={}
    
     for girl in girls:
         letterGirls.setdefault(girl[0],[]).append(girl)
     
     print letterGirls

    {'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
    まとめ:getは読み取り時、keyに発生しない異常、setdefaultは書き込み時、keyが存在しない時に発生する異常