본문으로 바로가기
반응형

Not using dict comprehensions

가끔씩 파이썬 2.7버전대 이전에 사용하던 오래된 방식으로 딕셔너리를 초기화하는 코드들이 있다.

새로운 딕셔너리 접근법은 기능적으로 동일함은 물론 좀 더 읽기 쉬운 형태를 제고한다.


Anti-pattern

numbers = [1,2,3]

# hard to read
my_dict = dict([(number,number*2) for number in numbers])

print(my_dict)  # {1: 2, 2: 4, 3: 6}

위 코드는 오래된 스타일로 딕셔너리를 초기화하는 예제이다.

문법적으로는 아무런 문제가 없지만 읽기 어렵다.


Best practice

numbers = [1, 2, 3]

my_dict = {number: number * 2 for number in numbers}

print(my_dict)  # {1: 2, 2: 4, 3: 6}

수정된 코드는 새로운 딕셔너리 초기화 방법이다. (파이썬 2.7버전에서 소개됨)


출처 : https://docs.quantifiedcode.com/python-anti-patterns/readability/not_using_a_dict_comprehension.html

반응형