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 !
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 !
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'}}]
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.
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}]