TIL # 40 : [Python] How to check if a dictionary is empty or not (Falsy Values in Python)

셀레스틴 허·2021년 1월 15일
0
post-thumbnail

The Error

  1. kwargs를 받는 함수를 선언했다.
  2. kwargs를 for문으로 돌리고 key 중 해당 조건과 맞는 값들만 딕셔너리인 name에 저장했다.
  3. 여기서 문제가 발생했다... 바로 해당 조건과 안 맞는 key가 있을 경우 모두 return되기 때문에 딕셔너리가 아무 값도 못 받고{}이 되는 것이다.
  4. 나는 name을 활용해 또 다른 조건문을 만들고 싶었는데 딕셔너리가 {} 즉 empty라 계속 막혔다. name is None도 안먹히는 상황이라 정말 많이 해맸다.

Solution

비어있는 딕셔너리 즉 Empty Dictionaries는 falsy value이기 때문에 bool()을 사용하면 해결할 수 있다.

Falsy Values:

그렇다면 Falsy Values는 뭐가 있을까?

Sequences and Collections

  1. Empty Lists : []
  2. Empty Tuples : ()
  3. Empty Dictionaries : {}
  4. Empty sets : set()
  5. Empty Strings : ""
  6. Empty ranges : range(0)

Numbers

  1. Zero of any numeric type
  2. Integer : 0
  3. Float : 0.0
  4. Complex : 0j

Constants

  1. None
  2. False

Then what makes a value True?

  1. Non-empty sequences or collections(lists, tuples, strings, dictionaries, sets)
  2. Numeric values that are not zero
  3. True

bool() 내장함수 쓰기

어떤 값이 T/F인지 bool()를 통해 알 수 있다.

구글만 있으면 어디든 갈 수 있어...

Reference
https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/#:~:text=Falsy%20values%20are%20values%20that,type%2C%20None%20%2C%20and%20False%20.

profile
Software Developer / 고통은 필연, 괴로움은 선택

0개의 댓글