티스토리 뷰

개발/파이썬

딕셔너리를 파일에 저장하기

맨날치킨 2022. 12. 20. 19:05
반응형

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

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

 

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

How to save a dictionary to a file?

어떻게 딕셔너리를 파일에 저장할까요?

 문제 내용 

I have problem with changing a dict value and saving the dict to a text file (the format must be same), I only want to change the member_phone field.

딕셔너리의 값을 변경하고 해당 딕셔너리를 텍스트 파일에 저장하는 문제가 있습니다. (포맷은 동일해야 함) 멤버 전화번호 필드만 변경하려고 합니다.

 

My text file is the following format:

텍스트 파일의 포맷은 다음과 같습니다.
memberID:member_name:member_email:member_phone

 

and I split the text file with:

그리고 다음과 같이 텍스트 파일을 분할합니다.
mdict={}
for line in file:
    x=line.split(':')
    a=x[0]
    b=x[1]
    c=x[2]
    d=x[3]
    e=b+':'+c+':'+d

    mdict[a]=e

 

When I try change the member_phone stored in d, the value has changed not flow by the key,

d에 저장된 멤버 전화번호를 변경하려고 할 때, 키를 따라 흐르지 않고 값이 변경된 것을 확인할 수 있습니다.
def change(mdict,b,c,d,e):
    a=input('ID')
    if a in mdict:
        d= str(input('phone'))
        mdict[a]=b+':'+c+':'+d
    else:
        print('not')

 

and how to save the dict to a text file with same format?

그리고 같은 포맷으로 딕셔너리를 텍스트 파일에 저장하는 방법은 무엇인가요?

 

 

 

 높은 점수를 받은 Solution 

Python has the pickle module just for this kind of thing.

파이썬에는 이런 종류의 작업을 위한 pickle 모듈이 있습니다.

 

These functions are all that you need for saving and loading almost any object:

다음 함수들은 거의 모든 객체를 저장하고 로드하는 데 필요합니다:
with open('saved_dictionary.pkl', 'wb') as f:
    pickle.dump(dictionary, f)
        
with open('saved_dictionary.pkl', 'rb') as f:
    loaded_dict = pickle.load(f)

 

In order to save collections of Python there is the shelve module.

Python 컬렉션을 저장하기 위해 shelve 모듈을 사용할 수도 있습니다.

 

 

 

 가장 최근 달린 Solution 

I like using the pretty print module to store the dict in a very user-friendly readable form:

딕셔너리를 매우 사용자 친화적인 읽기 가능한 형태로 저장하기 위해 pretty print 모듈을 사용합니다.
import pprint

def store_dict(fname, dic):
    with open(fname, "w") as f:
        f.write(pprint.pformat(dic, indent=4, sort_dicts=False))
        # note some of the defaults are: indent=1, sort_dicts=True

 

Then, when recovering, read in the text file and eval() it to turn the string back into a dict:

그런 다음, 복구할 때, 텍스트 파일을 읽고 eval()을 사용하여 문자열을 다시 딕셔너리로 변환합니다.
def load_file(fname):
    try:
        with open(fname, "r") as f:
            dic = eval(f.read())
    except:
        dic = {}
    return dic

 

 

출처 : https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file

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