source

python dict를 문자열로 변환한 후 되돌립니다.

bestscript 2022. 11. 22. 09:30

python dict를 문자열로 변환한 후 되돌립니다.

데이터를 사전 객체에 저장하는 프로그램을 작성 중인데, 이 데이터는 프로그램 실행 중 어느 시점에 저장했다가 프로그램을 다시 실행하면 다시 사전 객체에 로드해야 합니다.사전 개체를 파일에 쓰고 다시 사전 개체로 로드할 수 있는 문자열로 변환하려면 어떻게 해야 합니까?이렇게 하면 사전을 포함하는 사전을 지원할 수 있습니다.

여기서는 json 모듈이 좋은 솔루션입니다.피클에 비해 플레인 텍스트 출력만 가능하며 크로스 플랫폼과 크로스 버전이라는 장점이 있습니다.

import json
json.dumps(dict)

사전이 너무 크지 않으면 str + eval로 작업을 수행할 수 있습니다.

dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)

dict2 = eval(str1)

print(dict1 == dict2)

소스를 신뢰할 수 없는 경우 보안을 강화하기 위해 eval 대신 ast.literal_eval을 사용할 수 있습니다.

사용방법:

import json

# convert to string
input = json.dumps({'id': id })

# load to dict
my_dict = json.loads(input) 

Python 3의 내장 ost 라이브러리의 함수 literal_eval을 사용하지 않는 이유는 무엇입니까?eval 대신 literal_eval을 사용하는 것이 좋습니다.

import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)

실제 사전으로 출력합니다.

{'key1': 'key1value', 'key2': 'key2value'}

사전을 문자열로 변환하는 경우는 Python의 str() 메서드를 사용하는 것은 어떻습니까?

사전은 다음과 같습니다.

my_dict = {'key1': 'key1value', 'key2': 'key2value'}

이 작업은 다음과 같이 수행됩니다.

str(my_dict)

인쇄 예정:

"{'key1': 'key1value', 'key2': 'key2value'}"

이것은 당신이 원하는 대로 쉽다.

모듈을 사용하여 디스크에 저장하고 나중에 로드합니다.

사전을 JSON으로 변환(문자열)

import json 

mydict = { "name" : "Don", 
          "surname" : "Mandol", 
          "age" : 43} 

result = json.dumps(mydict)

print(result[0:20])

다음 정보를 얻을 수 있습니다.

{"name": "Don", "sur"

문자열을 사전으로 변환

back_to_mydict = json.loads(result) 

중국어에서는 다음과 같이 조정해야 합니다.

import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')

영속적인 파일 백업형 사전형 객체를 제공하는 모듈을 사용하는 것을 검토해야 할 것 같습니다.「실제」사전을 대신해 사용하기 쉬운 것은, 프로그램에 사전과 같이 사용할 수 있는 것을 거의 투과적으로 제공하기 때문입니다.이를 문자열로 명시적으로 변환한 후 파일에 쓸 필요가 없습니다(또는 그 반대).

가장 큰 차이점은 처음에 할 필요가 있다는 것입니다.open()처음 사용하기 전에 그 다음에close()끝나면(그리고 어쩌면)sync()입력, 에 따라서는writeback옵션)을 사용합니다.작성하는 "쉘프" 파일 개체는 일반 사전을 값으로 포함할 수 있으므로 논리적으로 중첩할 수 있습니다.

다음은 간단한 예입니다.

import shelve

shelf = shelve.open('mydata')  # open for reading and writing, creating if nec
shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
shelf.close()

shelf = shelve.open('mydata')
print shelf
shelf.close()

출력:

{'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}

속도에 관심이 있는 경우 json과 동일한 API를 가진 ujson(UltraJSON)을 사용합니다.

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

게 있을 거예요.json.dumps()메서드는 일부 개체 유형을 처리하는 데 도움이 필요합니다.

다음 항목에 대한 이 투고에서 가장 높은 답변이 인정됩니다.

import json
json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)

판독이 필요한 경우(JSON이나 XML 모두 IMHO가 아닙니다), 또는 판독이 필요 없는 경우 피클을 사용합니다.

기입하다

from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)

리딩백

from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev

RubyMarshl 'loads' 메서드로 로드한 후 dict 객체가 아니라 RubyString 타입의 키와 값이라는 것을 알게 되었습니다.

그래서 이렇게 했어요.

dic_items = dict.items()
new_dict = {str(key): str(value) for key, value in dic_items}

언급URL : https://stackoverflow.com/questions/4547274/convert-a-python-dict-to-a-string-and-back