Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python - 사전이 비어 있는지 확인

<시간/>

데이터 세트를 분석하는 동안 빈 사전을 처리해야 하는 상황을 만날 수 있습니다. 이 기사에서는 사전이 비어 있는지 여부를 확인하는 방법을 볼 것입니다.

if 사용

사전에 요소가 있으면 if 조건이 true로 평가됩니다. 그렇지 않으면 false로 평가됩니다. 따라서 아래 프로그램에서는 if 조건만 사용하여 사전의 빈 공간을 확인합니다.

예시

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
if dict1:
   print("dict1 is not empty")
else:
   print("dict1 is empty")
if dict2:
   print("dict2 is not empty")
else:
   print("dict2 is empty")

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty

bool() 사용

bool 메서드는 사전이 비어 있지 않으면 true로 평가됩니다. 그렇지 않으면 false로 평가됩니다. 그래서 우리는 사전이 비어 있는지에 대한 결과를 출력하기 위해 표현식에서 이것을 사용합니다.

예시

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
print("Is dict1 empty? :",bool(dict1))
print("Is dict2 empty? :",bool(dict2))

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : True
Is dict2 empty? : False