3

我有一份这份清单

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

我想在字典中转换 OrderedDict。

你知道我该怎么办吗?

谢谢 !

4

3 回答 3

10

要转换嵌套OrderedDict,您可以使用包json

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

[{'a': 'b', 'c': 'd', 'e': {'a': 'b', 'c': 'd'}}]
于 2019-06-07T12:28:09.587 回答
0

要转换嵌套的 OrderedDict,您可以使用 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}]
于 2021-02-17T10:31:19.967 回答
0

您可以构建一个递归函数来执行从 OrderedDict 到 dict 的转换,同时使用 isinstance 调用检查数据类型。

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

但是,请注意 OrderedDicts也是字典,并且支持键查找。

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

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

因此,如果您只需要访问字典允许的值,则不需要将 OrderedDicts 转换为 dicts,因为 OrderedDict 支持相同的操作。

于 2019-06-07T13:10:52.743 回答