파이썬 라이브러리 pprint
#012 파이썬 라이브러리 : pprint 데이터를 읽기 쉽게 출력
Python pprint(pretty-print) 모듈은 사전, 목록 및 튜플과 같은 복잡한 데이터 구조의 형식을 제어하는 쉬운 방법을 제공하는 유틸리티입니다. 보다 읽기 쉬운 형식으로 데이터 구조를 인쇄하는 데 사용할 수 있으며, 이는 출력의 가독성이 중요한 디버깅 및 기타 작업에 특히 유용합니다.
pprint 예제
import pprint
# Define a complex data structure
data = {'name': 'John Doe',
'age': 28,
'address': {'street': '123 Main St',
'city': 'Anytown',
'state': 'CA'},
'phone_numbers': ['555-1234', '555-5678', '555-9999']}
# Use pprint to print the data structure in a more readable format
print(data,'\n')
pprint.pprint(data)
▶ 결과
{'name': 'John Doe', 'age': 28, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA'}, 'phone_numbers': ['555-1234', '555-5678', '555-9999']}
{'address': {'city': 'Anytown', 'state': 'CA', 'street': '123 Main St'},
'age': 28,
'name': 'John Doe',
'phone_numbers': ['555-1234', '555-5678', '555-9999']}
▶ 설명
이 예에서는 중첩된 사전과 목록을 포함하는 사전 data를 정의합니다. 그런 다음 pprint 모듈의 pprint 함수를 사용하여 더 읽기 쉬운 형식으로 데이터 구조를 인쇄합니다.
보시다시피 출력은 데이터 구조를 더 쉽게 읽고 이해할 수 있는 방식으로 형식이 지정됩니다. 중첩된 사전과 목록은 들여 쓰기가 되어 별도의 줄에 표시되어 데이터 구조를 보다 쉽게 볼 수 있습니다.
전반적으로 pprint 모듈은 복잡한 데이터 구조를 보다 읽기 쉬운 방식으로 형식화하고 인쇄하는 데 유용한 도구를 제공합니다. 이것은 데이터의 전체 구조를 보기 어려울 수 있는 대규모 또는 중첩된 데이터 구조로 작업할 때 특히 유용할 수 있습니다.
더 복잡한 구조의 출력을 보겠습니다.
import pprint
# Example nested data structure
data = {
"name": "John Doe",
"age": 28,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phone_numbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
},
{
"type": "mobile",
"number": "555-9999"
}
],
"email": "johndoe@example.com"
}
# Use pprint to print the nested data structure in a more readable format
print(data,'\n')
pprint.pprint(data)
▶ 결과
{'name': 'John Doe', 'age': 28, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zip': '12345'}, 'phone_numbers': [{'type': 'home', 'number': '555-1234'}, {'type': 'work', 'number': '555-5678'}, {'type': 'mobile', 'number': '555-9999'}], 'email': 'johndoe@example.com'}
{'address': {'city': 'Anytown',
'state': 'CA',
'street': '123 Main St',
'zip': '12345'},
'age': 28,
'email': 'johndoe@example.com',
'name': 'John Doe',
'phone_numbers': [{'number': '555-1234', 'type': 'home'},
{'number': '555-5678', 'type': 'work'},
{'number': '555-9999', 'type': 'mobile'}]}
▶ 설명
pprint 출력은 중첩된 데이터 구조의 구조를 더 쉽게 읽고 이해할 수 있는 방식으로 형식이 지정됩니다. 중첩된 사전과 사전 목록은 들여 쓰기가 되어 별도의 줄에 표시되어 데이터 구조를 보다 쉽게 볼 수 있습니다.
전반적으로 pprint는 특히 데이터 구조를 디버깅하거나 시각화할 때 Python에서 복잡한 데이터 구조로 작업하기 위한 강력한 도구가 될 수 있습니다.
감사합니다.
Do it! SQL을 찾아 주셔서 감사합니다. ♥ 댓글이 큰 힘이 됩니다. |
'IT > 파이썬 라이브러리 (Python)' 카테고리의 다른 글
#014 파이썬 라이브러리 : enum으로 가독성을 높이자 (39) | 2023.04.09 |
---|---|
#013 파이썬 라이브러리 : bisect를 이용한 학점 부여 (38) | 2023.04.08 |
#011 파이썬 라이브러리 : heapq를 이용한 순위 매기기 (45) | 2023.04.06 |
#010 파이썬 라이브러리 : collections.defaultdict 딕셔너리 생성 및 초기화 한방에 (46) | 2023.04.05 |
#009 파이썬 라이브러리 : collections.Counter 사용된 단어 수를 세는 (51) | 2023.04.04 |
댓글