티스토리 뷰

개발/파이썬

파이썬 딕셔너리 저장하기

맨날치킨 2023. 3. 3. 19:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Storing Python dictionaries

파이썬 딕셔너리 저장하기

 문제 내용 

I'm used to bringing data in and out of Python using CSV files, but there are obvious challenges to this. Are there simple ways to store a dictionary (or sets of dictionaries) in a JSON or pickle file?

CSV 파일을 이용해서 파이썬에서 데이터를 불러오고 내보내는 것이 익숙한데, 이에 대한 도전 과제들이 명백합니다. JSON 또는 pickle 파일에 딕셔너리(또는 딕셔너리 세트)를 저장하는 간단한 방법이 있는지 알고 싶습니다.

 

For example:

예를 들면:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"

 

I would like to know both how to save this, and then how to load it back in.

저장하는 방법과, 그리고 저장된 것을 다시 불러오는 방법을 알고 싶습니다.

 

 

 

 높은 점수를 받은 Solution 

Pickle save:

Pickle로 저장:
try:
    import cPickle as pickle
except ImportError:  # Python 3.x
    import pickle

with open('data.p', 'wb') as fp:
    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)

 

See the pickle module documentation for additional information regarding the protocol argument.

프로토콜 인자에 대한 정보는 pickle 모듈 문서를 참조하세요.

 

Pickle load:

Pickle로 불러오기:
with open('data.p', 'rb') as fp:
    data = pickle.load(fp)

JSON save:

JSON으로 저장:
import json

with open('data.json', 'w') as fp:
    json.dump(data, fp)

 

Supply extra arguments, like sort_keys or indent, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

sort_keys나 indent와 같은 추가 인자를 제공하여 예쁘게 결과를 얻으세요. sort_keys 인자는 키를 알파벳순으로 정렬하고, indent는 데이터 구조를 indent=N 공백으로 들여쓸 것입니다.
json.dump(data, fp, sort_keys=True, indent=4)

 

JSON load:

JSON으로 불러오기:
with open('data.json', 'r') as fp:
    data = json.load(fp)

 

 

 가장 최근 달린 Solution 

For completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and (at least in Python 3) behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!

완성을 위해, ConfigParser와 configparser도 포함시켜야 합니다. 이것은 Python 2와 3의 표준 라이브러리입니다. 이 모듈은 config/ini 파일을 읽고 쓰며 (적어도 Python 3에서) 딕셔너리와 매우 비슷하게 동작합니다. 여러분의 config/ini 파일의 서로 다른 섹션에 여러 개의 딕셔너리를 저장하고 호출할 수 있는 장점이 있습니다. 멋지죠!

 

Python 2.7.x example.

Python 2.7.x 예시.
import ConfigParser

config = ConfigParser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config.add_section('dict1')
for key in dict1.keys():
    config.set('dict1', key, dict1[key])
   
config.add_section('dict2')
for key in dict2.keys():
    config.set('dict2', key, dict2[key])

config.add_section('dict3')
for key in dict3.keys():
    config.set('dict3', key, dict3[key])

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = ConfigParser.ConfigParser()
config2.read('config.ini')

dictA = {}
for item in config2.items('dict1'):
    dictA[item[0]] = item[1]

dictB = {}
for item in config2.items('dict2'):
    dictB[item[0]] = item[1]

dictC = {}
for item in config2.items('dict3'):
    dictC[item[0]] = item[1]

print(dictA)
print(dictB)
print(dictC)

 

Python 3.X example.

Python 3.X 예시.
import configparser

config = configparser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = configparser.ConfigParser()
config2.read('config.ini')

# ConfigParser objects are a lot like dictionaries, but if you really
# want a dictionary you can ask it to convert a section to a dictionary
dictA = dict(config2['dict1'] )
dictB = dict(config2['dict2'] )
dictC = dict(config2['dict3'])

print(dictA)
print(dictB)
print(dictC)

 

Console output

콘솔 출력
{'key2': 'keyinfo2', 'key1': 'keyinfo'}
{'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
{'z': '3', 'y': '2', 'x': '1'}

 

Contents of config.ini

config.ini의 내용
[dict1]
key2 = keyinfo2
key1 = keyinfo

[dict2]
k1 = hot
k2 = cross
k3 = buns

[dict3]
z = 3
y = 2
x = 1

 

 

출처 : https://stackoverflow.com/questions/7100125/storing-python-dictionaries

반응형
댓글
공지사항
최근에 올라온 글