Avoid KeyError in python dictionary

KeyError

test = {}
print test['a']

When you run this sample

KeyError: 'pagename'

Exception occurs. In order to avoid this, it is necessary to check in advance whether or not the key exists by using ʻin, has_key`, etc.

test = {}
if 'a' in test:
	print test['a']
else: 
	print ''

The code looks like this, but in the above cases, it seems that a convenient method called get is provided.

get(key[, default])

Quoted from Documents

If key is in the dictionary, it returns the value for key. Otherwise, it returns default. If no default is given, it defaults to None. Therefore, this method never throws a KeyError.

It seems that you can also specify the default value by specifying the second argument. Let's rewrite the above code using get

test = {}
print test.get('a')

It's very simple.

Recommended Posts

Avoid KeyError in python dictionary
Create a dictionary in Python
Avoid multiple loops in Python
Python dictionary
[Python] dictionary
Python dictionary
Quadtree in Python --2
Python in optimization
[Python] Memo dictionary
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Avoid nested loops in PHP and Python
Meta-analysis in Python
Unittest in python
[Python] Dictionary (hash)
Epoch in Python
Discord in Python
Decorator to avoid UnicodeEncodeError in Python 3 print ()
Sudoku in Python
nCr in python
N-Gram in Python
Programming in python
Python / dictionary> setdefault ()> Add if not in dictionary
Hash in Perl is a dictionary in Python
Plink in Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 18 in Python
Singleton pattern in Python
File operations in Python
Key input in Python
Daily AtCoder # 33 in Python
Python Basic Course (7 Dictionary)