Sudeep's Blog

Disorganized Thoughts in Organized Manner

Python dict update if/else vs try/except
For a quick update of a python dict, a try/catch block is a better alternative than if/else. for k in some_list: try: dct[k] = dct[k] + 1 except: dct[k] = 1 is more efficient than... for k in some_list: if k in dct.keys(): dct[k] = dct[k] + 1 else: dct[k] = 1 While later might be more readable. Obvious trick. A reminder to never forget it. (See this StackOverflow link: http://stackoverflow.com/questions/4512557/python-if-key-in-dict-vs-try-except.
Tweet
Back to Home