2019年10月23日 星期三

Python 檢查 dict 的索引值是否存在

Check if a given key exists in a dict


要檢查 dictionary 是否存在索引值
直接查會直接 KeyError
>>> d = {}
>>> d['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
這時就要靠 collections.defaultdict(default_factory)
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['a']
0
再回到檢查 dictionary 是否存在索引值的地方
from collections import defaultdict

s = 'mississippi'
my_dict = defaultdict(int) 
for key in s:
     if key in my_dict:
          my_dict[key] += 1
     else:
          my_dict[key] = 1

print(my_dict)
結果
defaultdict(, {'m': 1, 'i': 4, 's': 4, 'p': 2})

參考資料 :
https://docs.python.org/3/library/collections.html#defaultdict-examples
https://stackoverflow.com/questions/473099/check-if-a-given-key-already-exists-in-a-dictionary-and-increment-it

Related Posts:

  • Python Windows 換行符號與 Unix 換行轉換 ( convert CRLF to LF ) Convert CRLF to LF def convertCRLFtoLF(self, filename): WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(filename, "rb") as f: content = f.read() … Read More
  • Python 遞迴初學最近用 python 刷題 刷到要用 DFS 的題目,想用遞迴去寫才發現 python 沒有指標 看著討論的 python 大神寫的程式碼,發現都是 python 裡的參數都是指標 下面拿一題示範 0947 - Most Stones Removed with Same Row or Column class Solution: def removeStones(self, stones: List[L… Read More
  • Python UnitTest Unit Test      單元測試有一個通用模式 AAA原則,理解了就可以開始實作 Arrange   : 初始化物件、要用到的參數 Act   : 呼叫要測試的方法 Assert   : 驗證測試結果 Python Unit Test      unittest — Uni… Read More
  • Python bin() Python bin() bin(10) // 0b1010 type(bin(10)) // <class 'str'> bin(10)[2:] // 1010 … Read More
  • Python 檢查 dict 的索引值是否存在 Check if a given key exists in a dict 要檢查 dictionary 是否存在索引值 直接查會直接 KeyError >>> d = {} >>> d['a'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'a' 這時就要靠 … Read More

0 意見:

張貼留言

Popular Posts