How to convert an OrderedDict into a regular dict in python3

后端 未结 8 598
天命终不由人
天命终不由人 2020-12-04 09:43

I am struggling with the following problem: I want to convert an OrderedDict like this:

OrderedDict([(\'method\', \'constant\'), (\'data\', \'1.         


        
相关标签:
8条回答
  • 2020-12-04 09:51
    >>> 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'}
    >>>
    

    However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

    0 讨论(0)
  • 2020-12-04 09:53

    If somehow you want a simple, yet different solution, you can use the {**dict} syntax:

    from collections import OrderedDict
    
    ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
    regular = {**ordered}
    
    0 讨论(0)
  • 2020-12-04 09:56

    It is easy to convert your OrderedDict to a regular Dict like this:

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

    If you have to store it as a string in your database, using JSON is the way to go. That is also quite simple, and you don't even have to worry about converting to a regular dict:

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

    Or dump the data directly to a file:

    with open('outFile.txt','w') as o:
        json.dump(d, o)
    
    0 讨论(0)
  • 2020-12-04 09:56

    Here is what seems simplest and works in python 3.7

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

    Now to check this:

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

    NOTE: This also works, and gives same result -

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

    As well as this -

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

    Cheers

    0 讨论(0)
  • 2020-12-04 10:00

    A version that handles nested dictionaries and iterables but does not use the json module. Nested dictionaries become dict, nested iterables become list, everything else is returned unchanged (including dictionary keys and strings/bytes/bytearrays).

    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
    
    0 讨论(0)
  • 2020-12-04 10:16

    Even though this is a year old question, I would like to say that using dict will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be

    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
    
    0 讨论(0)
提交回复
热议问题