콘텐츠로 건너뛰기

pprint의 사용 방법과 고치는 방법은 무엇인가요?

[

Python의 Pretty Print를 사용하여 데이터 구조를 보기 좋게 만들기

Pythonista에게 데이터 처리는 필수적이지만 때로는 그 데이터가 아주 보기 좋지 않을 수도 있습니다. 컴퓨터는 형식에 신경을 쓰지 않지만, 좋은 형식이 없으면 사람들은 무엇인가를 읽기 힘들어할 수 있습니다. print() 함수를 사용하여 큰 사전이나 긴 목록을 출력하면 결과는 효율적이지만 보기에 좋지 않습니다.

Python의 pprint 모듈은 데이터 구조를 읽기 쉬운 예쁜 형태로 출력하는 데 사용할 수 있는 유틸리티 모듈입니다. 이것은 API 요청, 큰 JSON 파일 및 일반적인 데이터와 관련된 코드를 디버깅하는 데 특히 유용한 표준 라이브러리의 일부입니다.

이 튜토리얼이 끝나면 다음을 할 수 있게 될 것입니다:

  • pprint 모듈이 필요한 이유 이해하기
  • pprint() , PrettyPrinter 와 그 매개변수 사용 방법 배우기
  • **PrettyPrinter**의 인스턴스를 직접 생성할 수 있게 됩니다
  • 출력하는 대신 서식이 지정된 문자열 출력 저장하기
  • 재귀적인 데이터 구조를 출력하고 인식하기

무료 보너스: 파이썬 자습서를 이용해서 기초적인 Python 3 작업인 데이터 유형, 사전, 리스트 및 Python 함수 사용 등 Python 3의 기본 개념을 익힐 수 있는 Python Cheat Sheet를 받으세요.

Python의 Pretty Print가 필요한 이유 이해하기

pprint를 사용하기 전에 urllib를 사용하여 데이터를 요청하는 방법부터 살펴보겠습니다. Mock 사용자 정보를 얻기 위해 {JSON} Placeholder로 요청을 보냅니다. 먼저 HTTP GET 요청을 만들고 응답을 사전 형태로 저장합니다:

from urllib import request
response = request.urlopen("https://jsonplaceholder.typicode.com/users")
json_response = response.read()
import json
users = json.loads(json_response)

여기서 기본적인 GET 요청을 생성한 다음 json.loads()로 응답을 딕셔너리로 변환합니다. 딕셔너리가 변수에 저장되었으므로 print()을 사용하여 내용을 출력하는 것이 일반적인 다음 단계입니다:

print(users)

위의 코드를 실행하면 다음과 같은 출력이 표시됩니다:

[{'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenborough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}}, 'phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name': 'Romaguera-Crona', 'catchPhra
  • Understanding the Need for Python’s Pretty Print

    • Dealing with data is essential for any Pythonista, but sometimes that data is just not very pretty.
    • The output isn’t pretty when you use print() on large dictionaries or long lists.
  • Working With pprint

    • The pprint module in Python is a utility module that you can use to print data structures in a readable, pretty way.
    • It’s a part of the standard library that’s especially useful for debugging code dealing with API requests, large JSON files, and data in general.
  • Exploring Optional Parameters of pprint()

    • Summarizing Your Data: depth
    • Giving Your Data Space: indent
    • Limiting Your Line Lengths: width
    • Squeezing Your Long Sequences: compact
    • Directing Your Output: stream
    • Preventing Dictionary Sorting: sort_dicts
    • Prettifying Your Numbers: underscore_numbers
  • Creating a Custom PrettyPrinter Object

  • Getting a Pretty String With pformat()

  • Handling Recursive Data Structures

  • Conclusion