본문 바로가기
Programing Language/Python

[Python] 딕셔너리 키 존재여부 확인하기

by pcm9881 2023. 2. 21.

Python dictionary key exist

 

1. has_key  ( python 2에서만 사용가능 )

dict = {"hello": "world"}
if dict.has_key("hello): # True

- python2에서 사용가능.

- python3에서 사용시 AttributeError: 'dict' object has no attribute 'has_key' 에러를 확인하실 수 있습니다. 

 

2. in

dict = {'hello' : 'wolrd'}
if 'hello' in dict: # True

 

3. get

dict = {'hello' : 'wolrd'}
if dict.get('hello'): # True

 

 

참조

[python 3.0]: https://docs.python.org/3.1/whatsnew/3.0.html#builtins

 

What’s New In Python 3.0 — Python v3.1.5 documentation

What’s New In Python 3.0 Author:Guido van Rossum Release:3.1.5 Date:April 09, 2012 This article explains the new features in Python 3.0, compared to 2.6. Python 3.0, also known as “Python 3000” or “Py3K”, is the first ever intentionally backwards

docs.python.org

 

728x90

댓글