딕셔너리의 데이터를 보기 좋게 출력하는 방법에 대해서 알아보겠습니다. pretty print라고 하기도 합니다.
1. 딕셔너리를 보기 어렵게 출력하는 경우
딕셔너리를 단순히 print()로 출력하면, 한줄로 길게 출력되어 보기가 어렵습니다. 특히, 데이터가 많고 딕셔너리 안에 딕셔너리가 있다면 출력 결과는 더욱 보기 어렵습니다.
data = {'id': '1', 'title': 'foo', 'body': {'name': 'John Doe', 'age': '30'}, 'userId': '1'}
print(data)Output:
{'id': '1', 'title': 'foo', 'body': {'name': 'John Doe', 'age': '30'}, 'userId': '1'}2. pprint로 보기 좋게 출력
pprint()는 pretty print의 약자로, 딕셔너리를 인자로 전달하면 보기 좋게 데이터를 출력합니다.
from pprint import pprint
data = {'id': '1', 'title': 'foo', 'body': {'name': 'John Doe', 'age': '30'}, 'userId': '1'}
pprint(data)Output:
{'body': {'age': '30', 'name': 'John Doe'},
'id': '1',
'title': 'foo',
'userId': '1'}들여쓰기
indent 값을 인자로 전달하면, 전달된 개수만큼 들여쓰기를 하면서 출력합니다.
from pprint import pprint
data = {'id': '1', 'title': 'foo', 'body': {'name': 'John Doe', 'age': '30'}, 'userId': '1'}
pprint(data, indent=4)Output:
{ 'body': {'age': '30', 'name': 'John Doe'},
'id': '1',
'title': 'foo',
'userId': '1'}너비(width)
출력되는 행의 길이(width)가 길다면, width를 인자로 전달하여 최대 너비를 제한할 수 있습니다.
아래 예제는 width가 100일 때 데이터를 출력하는 코드입니다.
from pprint import pprint
data = {'id': '1', 'title': 'foo', 'body': {'name': 'John Doe', 'age': '30', 'hobby': ['baseball', 'PC game']}, 'userId': '1'}
pprint(data, width=100)Output:
{'body': {'age': '30', 'hobby': ['baseball', 'PC game'], 'name': 'John Doe'},
'id': '1',
'title': 'foo',
'userId': '1'}아래 예제는 width가 10일 때 데이터를 출력하는 코드입니다.
from pprint import pprint
data = {'id': '1', 'title': 'foo', 'body': {'name': 'John Doe', 'age': '30', 'hobby': ['baseball', 'PC game']}, 'userId': '1'}
pprint(data, width=10)Output:
{'body': {'age': '30',
'hobby': ['baseball',
'PC '
'game'],
'name': 'John '
'Doe'},
'id': '1',
'title': 'foo',
'userId': '1'}Loading script...
Related Posts
- Python - Yaml 파일 파싱하는 방법
- Python - 파일 내용 삭제
- Python - for문에서 리스트 순회 중 요소 값 제거
- Python - 두 리스트에서 공통 요소 값 찾기
- Python - 문자열 앞(뒤)에 0으로 채우기
- Python - 공백으로 문자열 분리
- Python - 중첩 리스트 평탄화(1차원 리스트 변환)
- Python - 16진수 문자열을 Int로 변환
- Python - 두 날짜, 시간 비교
- Python f-string으로 변수 이름, 값 쉽게 출력 (변수명 = )
- Python - nonlocal과 global 사용 방법
- Python 바다코끼리 연산자 := 알아보기
- Python - pip와 requirements.txt로 패키지 관리
- Python - 딕셔너리 보기 좋게 출력 (pprint)
- Python - Requests 사용 방법 (GET/POST/PUT/PATCH/DELETE)
- Python - 온라인 컴파일러 사이트 추천
- Python - os.walk()를 사용하여 디렉토리, 파일 탐색
- Python - 문자열 비교 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트의 첫번째 요소 제거
- Python - 리스트의 마지막 요소 제거
- Python 소수점 버림, 4가지 방법
- Python 코드 안에서 버전 확인 방법
- Python 소수점 반올림, round() 예제
- Python - 리스트 평균 구하기, 3가지 방법
- Python - bytes를 String으로 변환하는 방법
- Python - String을 bytes로 변환하는 방법
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - 람다(Lambda) 함수 사용 방법
- Python - dict 정렬 (Key, Value로 sorting)
- Python - range() 사용 방법 및 예제
- Python - 리스트를 문자열로 변환
- Python - 문자를 숫자로 변환 (String to Integer, Float)