본문 바로가기

언어/Python

[ Python ] 파이썬의 딕셔너리(dictionary)와 세트(set) comprehension

반응형

파이썬의 딕셔너리(dictionary)와 세트(set) comprehension은 리스트 comprehension과 유사하게, 간결한 구문으로 딕셔너리와 세트를 생성하는 방법입니다. 이 기능들은 데이터를 변환하거나 필터링하는 작업을 보다 쉽게 수행할 수 있게 해줍니다. 각각의 comprehension에 대해 자세히 설명하겠습니다.

1. 딕셔너리 Comprehension

딕셔너리 comprehension을 사용하면 기존 딕셔너리나 다른 이터러블(iterable)로부터 새로운 딕셔너리를 쉽게 생성할 수 있습니다. 기본 구문은 다음과 같습니다:

{key_expression: value_expression for item in iterable if condition}

예제 1: 기존 딕셔너리 변환

기존 딕셔너리의 값을 제곱하여 새로운 딕셔너리를 생성합니다.

original_dict = {'a': 1, 'b': 2, 'c': 3}
squared_dict = {key: value**2 for key, value in original_dict.items()}
print(squared_dict)  # 출력: {'a': 1, 'b': 4, 'c': 9}

예제 2: 조건을 사용한 딕셔너리 생성

기존 딕셔너리에서 값이 짝수인 항목만 필터링하여 새로운 딕셔너리를 생성합니다.

original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
even_dict = {key: value for key, value in original_dict.items() if value % 2 == 0}
print(even_dict)  # 출력: {'b': 2, 'd': 4}

예제 3: 두 리스트를 사용한 딕셔너리 생성

두 개의 리스트를 사용하여 딕셔너리를 생성합니다.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
combined_dict = {key: value for key, value in zip(keys, values)}
print(combined_dict)  # 출력: {'a': 1, 'b': 2, 'c': 3}

2. 세트 Comprehension

세트 comprehension을 사용하면 이터러블로부터 새로운 세트를 생성할 수 있습니다. 기본 구문은 다음과 같습니다:

{expression for item in iterable if condition}

예제 1: 리스트를 세트로 변환

리스트의 각 요소를 제곱하여 세트를 생성합니다.

numbers = [1, 2, 3, 4]
squared_set = {x**2 for x in numbers}
print(squared_set)  # 출력: {16, 1, 4, 9}

예제 2: 중복 요소 제거

리스트에서 중복된 요소를 제거하고 세트를 생성합니다.

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_set = {x for x in numbers}
print(unique_set)  # 출력: {1, 2, 3, 4, 5}

예제 3: 조건을 사용한 세트 생성

리스트에서 짝수만 포함하는 세트를 생성합니다.

numbers = [1, 2, 3, 4, 5, 6]
even_set = {x for x in numbers if x % 2 == 0}
print(even_set)  # 출력: {2, 4, 6}

3. 예제 코드 요약

다음은 위에서 설명한 모든 예제들을 하나의 코드로 묶은 것입니다.

# 딕셔너리 Comprehension 예제
original_dict = {'a': 1, 'b': 2, 'c': 3}
squared_dict = {key: value**2 for key, value in original_dict.items()}
print(squared_dict)  # {'a': 1, 'b': 4, 'c': 9}

even_dict = {key: value for key, value in original_dict.items() if value % 2 == 0}
print(even_dict)  # {'b': 2}

keys = ['a', 'b', 'c']
values = [1, 2, 3]
combined_dict = {key: value for key, value in zip(keys, values)}
print(combined_dict)  # {'a': 1, 'b': 2, 'c': 3}

# 세트 Comprehension 예제
numbers = [1, 2, 3, 4]
squared_set = {x**2 for x in numbers}
print(squared_set)  # {16, 1, 4, 9}

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_set = {x for x in numbers}
print(unique_set)  # {1, 2, 3, 4, 5}

numbers = [1, 2, 3, 4, 5, 6]
even_set = {x for x in numbers if x % 2 == 0}
print(even_set)  # {2, 4, 6}

이러한 딕셔너리와 세트 comprehension을 사용하면 보다 간결하고 읽기 쉬운 코드를 작성할 수 있습니다. 다양한 데이터를 변환하고 필터링하는 작업을 효율적으로 수행할 수 있습니다.

반응형