콘텐츠로 건너뛰기

딕셔너리를 반복하기: 파이썬에서 간편하게 사용하기

CodeMDD.io

파이썬에서 딕셔너리를 반복하는 방법

딕셔너리 반복에 대한 실질적인 지식은 더 좋고 견고한 코드를 작성하는 데 도움이 됩니다. 딕셔너리 반복을 통해 여러 예제를 작성하면 이해를 돕기위해 몇 가지 테스트 가능한 샘플 코드를 제공할 것입니다.

딕셔너리 반복을 시작하는 방법

딕셔너리를 반복하기 전에 먼저 딕셔너리에 데이터를 추가해야합니다. 딕셔너리는 중괄호 {}를 사용하여 생성하고 키-값 쌍으로 구성됩니다. 아래는 딕셔너리를 만드는 간단한 예시입니다.

person = {
"name": "John",
"age": 30,
"city": "New York"
}

이제부터 딕셔너리 반복을 시작해보겠습니다.

파이썬에서 딕셔너리를 반복하는 방법 이해하기

1. 딕셔너리 직접 탐색하기

딕셔너리를 반복하는 가장 간단한 방법은 직접 딕셔너리에 접근하는 것입니다. 아래 예제를 살펴보세요.

person = {
"name": "John",
"age": 30,
"city": "New York"
}
for key in person:
print(key, person[key])

위의 코드는 딕셔너리의 각 키-값 쌍에 대해 반복하고 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

name John
age 30
city New York

2. .items() 메서드를 사용하여 딕셔너리 키-값 쌍 반복하기

다음으로는 .items() 메서드를 사용하여 딕셔너리의 키-값 쌍을 반복하는 방법입니다. 아래 예제를 확인해보세요.

person = {
"name": "John",
"age": 30,
"city": "New York"
}
for key, value in person.items():
print(key, value)

위의 코드는 .items() 메서드를 사용하여 딕셔너리의 키와 값을 동시에 받아온 후, 이를 반복하며 출력합니다. 출력 결과는 다음과 같습니다.

name John
age 30
city New York

3. .keys() 메서드를 사용하여 딕셔너리 키 반복하기

.keys() 메서드를 사용하여 딕셔너리의 키를 반복하는 방법 역시 유용합니다. 아래 예제를 살펴보세요.

person = {
"name": "John",
"age": 30,
"city": "New York"
}
for key in person.keys():
print(key)

위의 코드는 .keys() 메서드를 사용하여 딕셔너리의 키를 받아온 후, 이를 반복하며 출력합니다. 출력 결과는 다음과 같습니다.

name
age
city

4. .values() 메서드를 사용하여 딕셔너리 값 반복하기

마지막으로 .values() 메서드를 사용하여 딕셔너리의 값만 반복하는 방법을 살펴보겠습니다. 아래 예제를 확인해보세요.

person = {
"name": "John",
"age": 30,
"city": "New York"
}
for value in person.values():
print(value)

위의 코드는 .values() 메서드를 사용하여 딕셔너리의 값만 받아온 후, 이를 반복하며 출력합니다. 출력 결과는 다음과 같습니다.

John
30
New York

딕셔너리 반복 중 값 변경하기

딕셔너리를 반복하는 동안 딕셔너리의 값을 변경하려면 어떻게 해야 할까요? 이를 해결하기 위해 임시 딕셔너리를 사용하고 .copy() 메서드를 이용하여 기존 딕셔너리를 복사할 수 있습니다. 아래 예제를 확인해보세요.

person = {
"name": "John",
"age": 30,
"city": "New York"
}
temp_person = person.copy()
for key in temp_person:
temp_person[key] = "Changed"
print(temp_person)
print(person)

위의 코드는 반복 중 임시 딕셔너리 temp_person에 값을 변경한 뒤, 변경된 temp_person와 원본 딕셔너리 person을 출력합니다. 출력 결과는 다음과 같습니다.

{'name': 'Changed', 'age': 'Changed', 'city': 'Changed'}
{'name': 'John', 'age': 30, 'city': 'New York'}

딕셔너리를 반복하면서 값을 변경할 때는 주의해야 합니다. 이러한 작업을 수행해야 할 경우 임시 딕셔너리를 사용하는 것이 좋습니다.

딕셔너리 반복 중 안전하게 항목 제거하기

딕셔너리를 반복하면서 딕셔너리의 항목을 제거해야 할 경우가 종종 있습니다. 그러나 딕셔너리를 반복하면서 항목을 제거하면 예기치 않은 동작이 발생할 수 있습니다. 이를 방지하기 위해 list() 함수를 사용하여 딕셔너리의 키를 리스트로 변환하고, 이를 반복하여 안전하게 항목을 제거할 수 있습니다. 아래 예제를 살펴보세요.

person = {
"name": "John",
"age": 30,
"city": "New York"
}
keys_to_remove = list(person.keys())
for key in keys_to_remove:
del person[key]
print(person)

위의 코드는 딕셔너리의 키를 list() 함수를 사용하여 리스트로 변환한 후, 이를 반복하며 딕셔너리 항목을 제거합니다. 제거 후 딕셔너리를 출력하면 빈 딕셔너리가 됩니다.

{}

딕셔너리 반복 중 항목을 안전하게 제거하려면 키를 별도의 리스트로 변환하고, 이를 반복하여 항목을 제거하는 것이 좋습니다.

for 루프 예제를 통한 딕셔너리 반복하기

이제 몇 가지 for 루프 예제를 통해 딕셔너리를 반복하는 방법에 대해 더 자세히 알아보겠습니다.

1. 특정 값에 따라 항목 필터링하기

특정 조건에 맞는 딕셔너리 항목만 필터링하고 싶다면 어떻게 해야 할까요? for 루프와 조건문을 함께 사용하여 이를 구현할 수 있습니다. 아래 예제를 확인해보세요.

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
for product, quantity in inventory.items():
if quantity > 5:
print(f"There are {quantity} {product}s left.")

위의 코드는 inventory 딕셔너리를 반복하면서 수량이 5개보다 많은 상품만을 필터링하여 출력합니다. 출력 결과는 다음과 같습니다.

There are 10 apples left.
There are 8 oranges left.

2. 키와 값을 이용하여 계산하기

딕셔너리의 키와 값을 사용하여 계산을 수행하려면 어떻게 해야 할까요? 이를 위해 for 루프를 사용하여 키와 값을 동시에 반복하고, 계산을 수행하면 됩니다. 아래 예제를 살펴보세요.

prices = {
"apple": 1.5,
"banana": 0.8,
"orange": 1.2,
"grape": 2.0
}
total_cost = 0
for product, quantity in inventory.items():
cost = prices[product] * quantity
total_cost += cost
print(f"The total cost is ${total_cost:.2f}")

위의 코드는 prices 딕셔너리와 inventory 딕셔너리를 반복하면서 상품 가격과 수량을 곱하여 총 비용을 계산합니다. 계산된 총 비용은 소수점 아래 두 자리까지 출력됩니다.

The total cost is $28.40

3. 키와 값을 교환하여 반복하기

딕셔너리의 키와 값을 서로 교환하여 반복하고 싶다면 어떻게 해야 할까요? 이를 위해 for 루프를 사용하여 딕셔너리의 키와 값을 zip() 함수를 이용하여 교환해야 합니다. 아래 예제를 확인해보세요.

grades = {
"John": 90,
"Emily": 85,
"Michael": 95,
"Jessica": 92
}
for score, student in zip(grades.values(), grades.keys()):
print(f"{student} scored {score}")

위의 코드는 grades 딕셔너리의 값을 키로, 키를 값으로 교환하고, 이를 zip() 함수를 이용하여 반복하며 이름과 점수를 출력합니다. 출력 결과는 다음과 같습니다.

John scored 90
Emily scored 85
Michael scored 95
Jessica scored 92

컴프리헨션을 이용한 딕셔너리 반복하기

컴프리헨션(Comprehension)은 파이썬에서 간결하고 강력한 기능 중 하나입니다. 딕셔너리의 컴프리헨션을 사용하면 반복을 더 간결하게 표현할 수 있습니다. 아래 예제를 살펴보세요.

1. 특정 값에 따라 항목 필터링하기: 재방문

이전에 살펴본 예제에서 다시 컴프리헨션을 사용하여 특정 조건에 맞는 항목만 필터링하는 방법을 확인해보겠습니다.

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
filtered_inventory = {product: quantity for product, quantity in inventory.items() if quantity > 5}
print(filtered_inventory)

위의 코드는 컴프리헨션을 사용하여 inventory 딕셔너리의 항목 중 수량이 5개보다 많은 항목만 필터링하여 filtered_inventory 딕셔너리를 생성합니다. 출력 결과는 다음과 같습니다.

{'apple': 10, 'orange': 8}

2. 키와 값을 교환하여 반복하기: 재방문

방금 전에 살펴본 예제에서 다시 컴프리헨션을 사용하여 딕셔너리의 키와 값을 서로 교환하는 방법을 확인해보겠습니다.

grades = {
"John": 90,
"Emily": 85,
"Michael": 95,
"Jessica": 92
}
flipped_grades = {score: student for student, score in grades.items()}
print(flipped_grades)

위의 코드는 컴프리헨션을 사용하여 grades 딕셔너리의 키와 값을 서로 교환하여 flipped_grades 딕셔너리를 생성합니다. 출력 결과는 다음과 같습니다.

{90: 'John', 85: 'Emily', 95: 'Michael', 92: 'Jessica'}

딕셔너리를 정렬 및 역순으로 반복하기

딕셔너리의 항목을 정렬하거나 역순으로 반복해야 할 때도 있습니다. 이를 위해 다음과 같은 방법들을 사용할 수 있습니다.

1. 키를 기준으로 정렬된 순서로 반복하기

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
for product in sorted(inventory):
print(product, inventory[product])

위의 코드는 sorted() 함수를 사용하여 inventory 딕셔너리의 키를 정렬한 후, 이를 반복하며 각 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

apple 10
banana 5
grape 2
orange 8

2. 값에 기반하여 정렬된 순서로 반복하기

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
for product in sorted(inventory, key=inventory.get):
print(product, inventory[product])

위의 코드는 sorted() 함수의 key 매개변수를 이용하여 inventory 딕셔너리의 값에 기반하여 정렬된 키를 얻고, 이를 반복하며 각 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

grape 2
banana 5
orange 8
apple 10

3. 컴프리헨션을 이용하여 딕셔너리를 정렬하기: 재방문

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
sorted_inventory = {product: inventory[product] for product in sorted(inventory)}
print(sorted_inventory)

위의 코드는 sorted() 함수를 사용하여 inventory 딕셔너리를 정렬한 후, 이를 컴프리헨션을 이용하여 새로운 딕셔너리 sorted_inventory에 저장합니다. 출력 결과는 다음과 같습니다.

{'apple': 10, 'banana': 5, 'grape': 2, 'orange': 8}

4. 내림차순으로 반복하기

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
for product in sorted(inventory, reverse=True):
print(product, inventory[product])

위의 코드는 sorted() 함수의 reverse 매개변수를 True로 설정하여 내림차순으로 정렬된 키를 얻고, 이를 반복하며 각 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

orange 8
grape 2
banana 5
apple 10

5. 딕셔너리의 역순으로 반복하기

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
for product in reversed(inventory):
print(product, inventory[product])

위의 코드는 reversed() 함수를 사용하여 inventory 딕셔너리의 역순으로 키를 얻고, 이를 반복하며 각 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

grape 2
orange 8
banana 5
apple 10

.popitem() 메서드를 사용하여 딕셔너리를 파괴적으로 반복하기

.popitem() 메서드를 사용하여 딕셔너리를 파괴적으로 반복할 수 있습니다. .popitem() 메서드는 딕셔너리에서 임의의 키-값 쌍을 반환한 다음 해당 항목을 삭제합니다. 아래 예제를 확인해보세요.

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
while inventory:
product, quantity = inventory.popitem()
print(product, quantity)

위의 코드는 inventory 딕셔너리가 비어 있을 때까지 .popitem() 메서드를 사용하여 임의의 키-값 쌍을 반복하고, 이를 출력합니다. 출력 결과는 다음과 같습니다.

grape 2
orange 8
banana 5
apple 10

.popitem() 메서드는 딕셔너리에서 항목을 제거하므로 주의해야 합니다.

빌트인 함수를 사용하여 암묵적으로 딕셔너리 반복하기

때로는 빌트인 함수를 사용하여 딕셔너리를 암묵적으로 반복하는 것이 유용한 경우가 있습니다.

1. map() 함수를 사용하여 딕셔너리 항목에 변환 적용하기

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
doubled_inventory = {product: quantity * 2 for product, quantity in map(lambda item: (item[0], item[1]), inventory.items())}
print(doubled_inventory)

위의 코드는 map() 함수와 람다 함수를 사용하여 inventory 딕셔너리의 항목을 변환하고, 이를 컴프리헨션을 이용하여 doubled_inventory 딕셔너리를 생성합니다. 출력 결과는 다음과 같습니다.

{'apple': 20, 'banana': 10, 'orange': 16, 'grape': 4}

2. filter() 함수를 사용하여 딕셔너리 항목 필터링하기

inventory = {
"apple": 10,
"banana": 5,
"orange": 8,
"grape": 2
}
filtered_inventory = {product: quantity for product, quantity in filter(lambda item: item[1] > 5, inventory.items())}
print(filtered_inventory)

위의 코드는 filter() 함수와 람다 함수를 사용하여 inventory 딕셔너리의 항목을 필터링하고, 이를 컴프리헨션을 이용하여 filtered_inventory 딕셔너리를 생성합니다. 출력 결과는 다음과 같습니다.

{'apple': 10, 'orange': 8}

여러 개의 딕셔너리를 하나로 합쳐서 반복하기

때로는 여러 개의 딕셔너리를 하나로 합쳐서 반복해야 할 때가 있습니다. 이를 위해 chain() 함수나 ChainMap()을 사용할 수 있습니다.

1. chain() 함수를 사용하여 여러 개의 딕셔너리 반복하기

from itertools import chain
inventory1 = {
"apple": 10,
"banana": 5
}
inventory2 = {
"orange": 8,
"grape": 2
}
for product, quantity in chain(inventory1.items(), inventory2.items()):
print(product, quantity)

위의 코드는 chain() 함수를 사용하여 inventory1 딕셔너리와 inventory2 딕셔너리를 하나로 합칩니다. 그리고 합친 딕셔너리를 반복하며 각 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

apple 10
banana 5
orange 8
grape 2

2. ChainMap()을 사용하여 여러 개의 딕셔너리 반복하기

from collections import ChainMap
inventory1 = {
"apple": 10,
"banana": 5
}
inventory2 = {
"orange": 8,
"grape": 2
}
combined_inventory = ChainMap(inventory1, inventory2)
for product, quantity in combined_inventory.items():
print(product, quantity)

위의 코드는 ChainMap()을 사용하여 inventory1 딕셔너리와 inventory2 딕셔너리를 하나로 합친 combined_inventory를 만듭니다. 그리고 합쳐진 딕셔너리를 반복하며 각 키와 값을 출력합니다. 출력 결과는 다음과 같습니다.

apple 10
banana 5
orange 8
grape 2

딕셔너리 반복을 위한 얻을 수 있는 주요 내용

이제 앞서 다룬 주요 내용을 정리해보겠습니다.

  • 파이썬에서 딕셔너리를 반복하는 방법에는 직접 딕셔너리 탐색, .items() 메서드를 사용한 키-값 쌍 반복, .keys() 메서드를 사용한 키 반복, .values() 메서드를 사용한 값 반복이 있습니다.
  • 딕셔너리 반복 중 값 변경을 해야 할 경우 동시 변경 문제를 방지하기 위해 임시 딕셔너리를 사용하는 것이 좋습니다.
  • 딕셔너리 반복 중 안전하게 항목을 제거하기 위해 임시 키 리스트를 만들고, 이를 반복하여 안전하게 항목을 제거할 수 있습니다.
  • 컴프리헨션을 이용하여 딕셔너리를 반복하면 코드가 더 간결해집니다.
  • .popitem() 메서드를 사용하여 딕셔너리를 파괴적으로 반복할 수 있습니다.
  • map() 함수와 filter() 함수를 사용하여 딕셔너리 항목을 변환하거나 필터링할 수 있습니다.
  • 여러 개의 딕셔너리를 하나로 합쳐서 반복하려면 chain() 함수나 ChainMap()을 사용할 수 있습니다.

요약

이 튜토리얼에서는 파이썬에서 딕셔너리를 반복하는 방법에 대해 상세하게 알아보았습니다. 딕셔너리를 반복하는 방법을 잘 이해하면 코드를 더 효율적으로 작성할 수 있으며 실제 문제를 해결하는데 도움이 될 것입니다. 딕셔너리 반복에 대한 이해를 바탕으로 여러분은 파이썬에서 딕셔너리를 보다 잘 활용할 수 있을 것입니다.