program tip

OrderedDict를 python3에서 일반 dict로 변환하는 방법

radiobox 2020. 9. 25. 07:44
반응형

OrderedDict를 python3에서 일반 dict로 변환하는 방법


다음 문제로 어려움을 겪고 있습니다. 다음과 OrderedDict같이 변환하고 싶습니다.

OrderedDict([('method', 'constant'), ('data', '1.225')])

다음과 같은 일반 사전으로 :

{'method': 'constant', 'data':1.225}

데이터베이스에 문자열로 저장해야하기 때문입니다. 변환 후 주문은 더 이상 중요하지 않으므로 어쨌든 주문한 기능을 절약 할 수 있습니다.

힌트 나 해결책에 감사드립니다.


>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

그러나 데이터베이스에 저장하려면 JSON 또는 Pickle과 같은 형식으로 변환하는 것이 훨씬 좋습니다. Pickle을 사용하면 주문도 보존 할 수 있습니다!


이것은 1 년 된 질문이지만, dict주문 된 dict 내에 주문 된 dict가있는 경우 사용하는 것이 도움이되지 않는다고 말하고 싶습니다 . 재귀 순서가 지정된 사전을 변환 할 수있는 가장 간단한 방법은 다음과 같습니다.

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict

다음 과 같이 OrderedDict일반 으로 변환하는 것은 쉽습니다 Dict.

dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))

데이터베이스에 문자열로 저장해야하는 경우 JSON을 사용하는 것이 좋습니다. 그것은 또한 매우 간단하며 일반으로 변환하는 것에 대해 걱정할 필요가 없습니다 dict.

import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)

또는 데이터를 파일에 직접 덤프합니다.

with open('outFile.txt','w') as o:
    json.dump(d, o)

json모듈 을 사용하지 않고 재귀 버전을 찾는 경우 :

def ordereddict_to_dict(value):
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = ordereddict_to_dict(v)
    return dict(value)

다음은 가장 간단하고 파이썬 3.7에서 작동하는 것입니다.

d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d)  # Now a normal dict

간단한 방법

>>import json 
>>from collection import OrderedDict

>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))

참고 URL : https://stackoverflow.com/questions/20166749/how-to-convert-an-orderdict-into-a-regular-dict-in-python3

반응형