<Python> dictionary, JSON

Google 아니고 Joogle·2023년 3월 28일
0

Python

목록 보기
1/5

✅dictionary

1️⃣dictionary

  • 딕셔너리 타입은 immutable한 keymutable한 value로 맵핑되어 있는 순서가 없는 집합
  • key 값으로 immutable한 값 (e.g. int, tuple, float, bool) 사용이 가능하지만 mutable한 값 (e.g. set, list, dict) 은 사용이 불가능
  a={(1,5) : 5, (3,3): 3} # key로 tuple 사용 가능
  a={{1,5} : 5, {3,3}: 3} # key로 set 사용 불가능
  • 값은 중복될 수 있지만, 키가 중복되면 마지막 값으로 덮어씌워짐
  • 순서가 없기 때문에 인덱스로 접근이 불가능하고, 키로 접근할 수 있음

2️⃣dictionary 복사

dictionary 자료 구조는 immutable하기 때문에 얕은 복사와 깊은 복사를 구분해야 함

얕은 복사 (shallow copy) : .copy() , b=dict(a)

  • 변수를 복사했지만 참조한 곳은 동일하기 때문에 같은 변수를 가리키고 있는 것
  • 즉, 값을 변경하면 다른 변수에도 영향을 끼침
>>> a= {'kim' : [1,2,3], 'hong' : [4,5,6]}
>>> b=a.copy()
>>> b['kim'].append(4)
>>> b
{'kim' : [1,2,3,4], 'hong' : [4,5,6]}
>>>a
{'kim' : [1,2,3,4], 'hong' : [4,5,6]}

깊은 복사 (deep copy) : b=copy.deepcopy(a)

  • 내부에 있는 객체를 모두 새롭게 만들어주는 작업

import copy

>>> a= {'kim' : [1,2,3], 'hong' : [4,5,6]}
>>> b=copy.deepcopy(a)
>>> b['kim'].append(4)
>>> b
{'kim' : [1,2,3,4], 'hong' : [4,5,6]}
>>> a
a= {'kim' : [1,2,3], 'hong' : [4,5,6]}

3️⃣dictionary for문

key값 출력

a= {'kim' : [1,2,3], 'hong' : [4,5,6]}
for key in a :
	print(key)
  • 순서는 임의적

value 값 출력: .value()

for value in a.value() :
	print(value)

key, value 값 한꺼번에 출력: .items()

for key, value in a.items() :
	print(key, value)

✅JSON

import json하여 사용하며, json은 string 형태로 변환되기 때문에 dictionary를 통해 key를 통한 데이터 접근이 불가능

1️⃣JSON to Dictionary - json.loads()

#JSON 파일을 읽고 문자열을 딕셔너리로 변환
def create_dict(filename):
    with open(filename) as file:
        json_str= file.read()
        return json.loads(json_str)

2️⃣Dictionary to JSON - json.dumps()

#JSON 파일을 읽고 딕셔너리를 JSON 형태의 문자열로 변환
def create_json(dictionary, filename):
    with open(filename, 'w') as file:
        json_str=json.dumps(dictionary)
        file.write(json_str)

Reference

profile
Backend 개발자 지망생

0개의 댓글