[ Python ] 문자열 dict{}를 딕셔너리 type으로 만들기

이유진·2023년 6월 7일
0

Python

목록 보기
9/9

환경변수로 {}형태지만 str type으로 반환되는 데이터를 조건처리를 위해,
dict type으로 변환해야하는 과정에서 문제가 발생하였다.

환경변수에서 불러온 데이터 형태는 이러하다.

a = {"id": 0, "exp": 0, "level": 0, "status": False}

육안으로 확인시 dict 으로 보여지지만,
type을 확인해보면, str 으로 보여진다.

str type의 딕셔너리를 dict type으로 변경하기 위해,

print(dict(a))

# 출력결과 :
dictionary update sequence element #0 has lengh 1; 2 is required

위와 같은 에러가 발생한다.

다른 방법으로 json을 이용하면 된다고 하여 적용해 보았다.

import json

print(json.loads(a))

# 출력결과
json.decoder.JSONDecodeError: Expecting value: line 1 column 43 (char 42)

위와 같은 json decoder 에러가 발생한다.

그래서 다른 블로그를 통해서
다른 해결책인 literal_eval을 통해서 해결하였다.

from ast import literal_eval

print(literal_eval(a))

# 출력결과
{"id": 0, "exp": 0, "level": 0, "status": False} # type dict

[ 참고 vlolg ]
https://mizykk.tistory.com/31

profile
차근차근 배워나가는 주니어 개발자

0개의 댓글