1、將JSON數據轉爲 OrderedDict 字典格式!
dic = json.loads(line, object_pairs_hook=collections.OrderedDict)
2、定義字典,collections類中的defaultdict()方法可以避免,當Key不存在時,會引發‘KeyError’異常;指定類型,當key不存在時,返回類型的值
collections.defaultdict(int)
3、assert 不滿足條件則拋出異常,滿足則什麼不發生!
assert 4 == 4 # 滿足條件,沒反應
assert 4 == 5
報錯:
File "<ipython-input-42-0e54103c2322>", line 1, in <module>
assert 4 == 5
AssertionError
assert 發生錯誤時 拋出自定義異常信息:
a = " "
b = "this is"
assert a == b, (a, b)
錯誤信息:
File "<ipython-input-18-1bf2c660766f>", line 1, in <module>
assert a == b, (a, b)
AssertionError: (' ', 'this is')
assert a == b, ("出現錯誤了!")
File "<ipython-input-19-6bb6f5697a89>", line 1, in <module>
assert a == b, ("出現錯誤了!")
AssertionError: 出現錯誤了!