개발/파이썬

Dictionary 형태의 문자열 표현을 Dictionary로 변환하기

맨날치킨 2022. 12. 10. 15:05
반응형

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

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

 

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

Convert a String representation of a Dictionary to a dictionary

Dictionary 형태의 문자열 표현을 Dictionary로 변환하기

 문제 내용 

How can I convert the str representation of a dict, such as the following string, into a dict?

다음 문자열과 같은 딕트의 str 표현을 dict로 변환하려면 어떻게 해야 하나요?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"

 

I prefer not to use eval. What else can I use?

나는 eval을 사용하지 않는 것을 선호합니다. 그 밖에 무엇을 사용할 수 있습니까?

 

The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.

이것의 주된 이유는 제 동료 중 작업한 클래스 중 하나가 모든 입력을 문자열로 변환하기 때문입니다. 저는 이 문제를 해결하기 위해 그의 클래스를 수정할 기분이 아닙니다.

 

 

 

 높은 점수를 받은 Solution 

You can use the built-in ast.literal_eval:

내장된 ast.literal_eval:을 사용할 수 있습니다.
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}

 

For example:

예:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
    names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

 

 

 가장 최근 달린 Solution 

Optimized code of Siva Kameswara Rao Munipalle

시바 카메스와라 라오 무니팔레의 최적화된 코드
s = s.replace("{", "").replace("}", "").split(",")
            
dictionary = {}

for i in s:
    dictionary[i.split(":")[0].strip('\'').replace("\"", "")] = i.split(":")[1].strip('"\'')
            
print(dictionary)

 

 

출처 : https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary

반응형