21.12.02 JSON, CSV

2021. 12. 4. 12:25작업/데이터분석

실습2

# 사용자가 시청한 작품의 리스트를 저장합니다. 수정하지 마세요. 
user_to_titles = {
    1: [271, 318, 491],
    2: [318, 19, 2980, 475],
    3: [475],
    4: [271, 318, 491, 2980, 19, 318, 475],
    5: [882, 91, 2980, 557, 35],
}
def get_user_to_num_titles(user_to_titles):
    user_to_num_titles = {}
    
    # 아래 함수를 완성하세요.
    for user,titles in user_to_titles.items(): # .items는 딕셔너리의 키와 벨류를 꺼내오는 듯?
        # print(user) 1
        # print(titles) [271,318,491]
        user_to_num_titles[user]=len(titles) # 각 유저별로 본 작품 수 넣기
    
    return user_to_num_titles
    

# 아래 주석을 해제하고 결과를 확인해보세요.  
print(get_user_to_num_titles(user_to_titles))

JSON 파일 포멧 중 하나

Java Script Object Notation

- 웹 환경에서 데이터를 주고받는 가장 표준적인 방식

- 키를 이용해 원하는 데이터만 빠르게 추출 가능

- 데이터가 쉽게 오염되지 않음

- 다른 포맷에 비해 용량이 조금 크다

- JSON과 딕셔너리는 거의 똑같이 생김

 

JSON -> loads() -> 딕셔너리

딕셔너리 -> dumps() -> JSON

# json 패키지를 임포트합니다.
import json



#JSON 파일을 읽고 문자열을 딕셔너리로 변환합니다.
def create_dict(filename):
    with open(filename) as file:
        json_string = file.read()
        
        # 함수를 완성하세요.
        return json.loads(json_string)



#JSON 파일을 읽고 딕셔너리를 JSON 형태의 문자열로 변환합니다.
def create_json(dictionary, filename):
    with open(filename, 'w') as file:
        # 함수를 완성하세요.
        json_string = json.dumps(dictionary)
        file.write(json_string)

 

집합

- 중복이 없다

- 순서가 없다.. 리스트는 [3,2,1]과 [1,2,3]이 다름 근데 집합은 아님.

 

 

CSV

- Comma Separated Value

- 각 열이 특정한 의미를 지님

- 용량이 작다, 구분 문자로 구분한다(, |)

- 단점 : 오염이 쉽다..

# CSV, JSON 모듈을 임포트합니다.
import csv
import json
from elice_utils import EliceUtils

elice_utils = EliceUtils()

def books_to_json(src_file, dst_file):
    # 아래 함수를 완성하세요.
    books = []
    with open(src_file) as src:
        reader = csv.reader(src, delimiter=',')
        
        # 각 줄 별로 대응되는 book 딕셔너리를 만듭니다.
        for row in reader:
            # 책 정보를 저장하는 딕셔너리를 생성합니다.
            book = {
                'title': row[0],
                'author':row[1],
                'genre':row[2],
                'pages':int(row[3]),
                'publisher':row[4]
            }
            books.append(book)
    
    with open(dst_file, 'w') as dst:
        # JSON 형식으로 dst_file에 저장합니다.
        json_string = json.dumps(books)
        dst.write(json_string)


# 아래 주석을 해제하고 결과를 확인해보세요.  
src_file = 'books.csv'
dst_file = 'books.json'
books_to_json(src_file, dst_file)
elice_utils.send_file(dst_file)