programing

python3에서 OrderedDict를 정규 dict로 변환하는 방법

instargram 2023. 7. 21. 20:35
반응형

python3에서 OrderedDict를 정규 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과 같은 형식으로 변환하는 것이 훨씬 좋습니다.피클을 사용하면 질서도 유지할 수 있습니다!

비록 이것이 1년 전의 질문이지만, 저는 사용하는 것을 말하고 싶습니다.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)

다음은 python 3.7에서 작동하는 단순해 보이는 것입니다.

from collections import OrderedDict

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

이제 확인해 보겠습니다.

>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True

참고: 이 기능도 작동하며 동일한 결과를 제공합니다.

>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True

이뿐만 아니라...

>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True

건배.

"dict_constructor" 매개 변수를 사용할 수 있습니다.

xmltodict.parse(text, attr_prefix='',dict_constructor=dict)

데이터 구조에 내부(내포)가 포함될 수 있는 경우OrderedDictPython의 내장 메커니즘을 활용해야 합니다.

다음에 대한 복사 동작을 재정의할 수 있습니다.OrderedDictPython의 모듈(에서 사용하기도 함)을 통해.그런 다음 Python의 내장 기능을 사용하여 변환을 수행할 수 있습니다.

import copy
import copyreg
from collections import OrderedDict

def convert_nested_ordered_dict(x):
    """
    Perform a deep copy of the given object, but convert
    all internal OrderedDicts to plain dicts along the way.

    Args:
        x: Any pickleable object

    Returns:
        A copy of the input, in which all OrderedDicts contained
        anywhere in the input (as iterable items or attributes, etc.)
        have been converted to plain dicts.
    """
    # Temporarily install a custom pickling function
    # (used by deepcopy) to convert OrderedDict to dict.
    orig_pickler = copyreg.dispatch_table.get(OrderedDict, None)
    copyreg.pickle(
        OrderedDict,
        lambda d: (dict, ([*d.items()],))
    )
    try:
        return copy.deepcopy(x)
    finally:
        # Restore the original OrderedDict pickling function (if any)
        del copyreg.dispatch_table[OrderedDict]
        if orig_pickler:
            copyreg.dispatch_table[OrderedDict] = orig_pickler

Python의 내장된 복사 인프라를 사용하는 것만으로도 이 솔루션은 다음과 같은 점에서 여기에 제시된 다른 모든 답변보다 우수합니다.

  • 중첩을 포함한 임의 데이터 계층에 대해 작동합니다.OrderedDicts.

  • JSON 데이터 이상의 용도로 사용할 수 있습니다.

  • 가능한 각 요소 유형에 대해 특수 논리를 구현할 필요가 없습니다(예:list,tuple등)

  • deepcopy()컬렉션 내의 중복 개체를 올바르게 처리합니다.

    x = [1,2,3]
    d = {'a': x, 'b': x}
    assert d['a'] is d['b']
    
    d2 = copy.deepcopy(d)
    assert d2['a'] is d2['b']
    

    당사의 솔루션은 다음을 기반으로 하기 때문에deepcopy()우리도 같은 이점을 갖게 될 겁니다

  • 이 솔루션은 또한 다음과 같은 특성을 변환합니다.OrderedDict컬렉션 요소뿐만 아니라:

    class C:
        def __init__(self, a):
            self.a = a
    
        def __repr__(self):
            return f"C(a={self.a})"
    
    c = C(OrderedDict([(1, 'one'), (2, 'two')]))
    print("original: ", c)
    print("converted:", convert_nested_ordered_dict(c))
    
    original:  C(a=OrderedDict([(1, 'one'), (2, 'two')]))
    converted: C(a={1: 'one', 2: 'two'})
    

그것은 간단한 방법입니다.

>>import json 
>>from collection import OrderedDict

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

한 항목을 하지만 된첩사및가항한능목처을만지버않을 입니다.json모듈. 중된사다같과습다니음은전첩▁becomearies가 됩니다.dict 반복 한 항목은 첩반 복가항됩니다이목능이 됩니다.list다른 모든 항목은 변경되지 않고 반환됩니다(사전 키 및 문자열/바이트/바이트/바이트 배열 포함).

def recursive_to_dict(obj):
    try:
        if hasattr(obj, "split"):    # is string-like
            return obj
        elif hasattr(obj, "items"):  # is dict-like
            return {k: recursive_to_dict(v) for k, v in obj.items()}
        else:                        # is iterable
            return [recursive_to_dict(e) for e in obj]
    except TypeError:                # return everything else
        return obj

언급URL : https://stackoverflow.com/questions/20166749/how-to-convert-an-ordereddict-into-a-regular-dict-in-python3

반응형