3

I have a this list

a = [OrderedDict([('a','b'), ('c','d'), ('e', OrderedDict([('a','b'), ('c','d') ]))])]

and I want to convert the OrderedDict in dictionary.

Do you know how could I do ?

Thank you !

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388

3 Answers3

8

To convert a nested OrderedDict, you could use package json

>>> import json
>>> json.loads(json.dumps(a))

[{'a': 'b', 'c': 'd', 'e': {'a': 'b', 'c': 'd'}}]
Yuan JI
  • 2,487
  • 2
  • 15
  • 26
  • I tried your solution but I have something like this : `{ValueError}dictionary update sequence element #0 has length x; y is required` – Gregory Palmer Jun 07 '19 at 12:30
0

You can build a recursive function to do the conversion from OrderedDict to dict, checking for the datatypes using isinstance calls along the way.

from collections import OrderedDict

def OrderedDict_to_dict(arg):
    if isinstance(arg, (tuple, list)): #for some iterables. might need modifications/additions?
        return [OrderedDict_to_dict(item) for item in arg]

    if isinstance(arg, OrderedDict): #what we are interested in
        arg = dict(arg)

    if isinstance(arg, dict): #next up, iterate through the dictionary for nested conversion
        for key, value in arg.items():
            arg[key] = OrderedDict_to_dict(value)

    return arg

a = [OrderedDict([('a','b'), ('c','d'), ('e', OrderedDict([('a','b'), ('c','d') ]))])]


result = OrderedDict_to_dict(a)
print(result)
#Output:
[{'a': 'b', 'c': 'd', 'e': {'a': 'b', 'c': 'd'}}]

However, note that OrderedDicts are dictionaries too, and support key lookups.

print(a[0]['e'])
#Output:
OrderedDict([('a', 'b'), ('c', 'd')])

a[0]['e']['c']
#Output:
'd'

So, you should not need to convert the OrderedDicts to dicts if you just need to access the values as a dictionary would allow, since OrderedDict supports the same operations.

Paritosh Singh
  • 5,442
  • 2
  • 10
  • 31
0

To convert a nested OrderedDict, you could use For:

from collections import OrderedDict
a = [OrderedDict([('id', 8)]), OrderedDict([('id', 9)])]
data_list = []
for i in a:
    data_list.append(dict(i))
print(data_list)
#Output:[{'id': 8}, {'id': 9}]