📜  如何将嵌套的 OrderedDict 转换为 dict?

📅  最后修改于: 2022-05-13 01:55:24.093000             🧑  作者: Mango

如何将嵌套的 OrderedDict 转换为 dict?

在本文中,我们将讨论如何将嵌套的OrderedDict转换为dict ?在此之前,我们必须先了解一些概念:

  • Python中的字典是数据值的无序集合,用于像映射一样存储数据值,与其他仅将单个值作为元素保存的数据类型不同,字典保存键:值对。字典中提供了键值,以使其更加优化。
  • OrderedDict是一个字典子类,它记住第一次插入键的顺序。
  • dict()OrderedDict()之间的唯一区别在于: OrderedDict保留键插入的顺序。常规 dict 不跟踪插入顺序并迭代它以任意顺序给出值。相比之下,插入项的顺序由OrderedDict记住。

为了定义嵌套的OrderedDict ,我们在Python中使用collections模块。

Python3
#import package
from collections import OrderedDict
  
# define OrderedDict
od1 = OrderedDict([('1', 'one'), ('2', 'two')])
print(type(od1))
print(od1)
  
# define nested OrderedDict
od2 = OrderedDict([('1', 'one'), 
                   ('2', OrderedDict([('-2', 
                                       '-ive'), 
                                      ('+2', 
                                       '+ive')]))])
print(type(od2))
print(od2)


Python3
# import package
from collections import OrderedDict
  
# define OrderedDict
od1 = OrderedDict([('1', 'one'), ('2', 'two')])
  
# convert to dict
od1 = dict(od1)
  
# display dictionary
print(type(od1))
print(od1)


Python3
# import package
from collections import OrderedDict
import json
  
# define nested OrderedDict
od2 = OrderedDict([('1', 'one'), 
                   ('2', OrderedDict([('-2', 
                                       '-ive'), 
                                      ('+2', 
                                       '+ive')]))])
# convert to dict
od2 = json.loads(json.dumps(od2))
  
# display deictionary
print(type(od2))
print(od2)


输出:

我们可以在一行中将OrderedDict转换为dict ,但这仅适用于简单的OrderedDict 不适用于嵌套的 OrderedDict。

蟒蛇3

# import package
from collections import OrderedDict
  
# define OrderedDict
od1 = OrderedDict([('1', 'one'), ('2', 'two')])
  
# convert to dict
od1 = dict(od1)
  
# display dictionary
print(type(od1))
print(od1)

输出:


{'1': 'one', '2': 'two'}

因此,要将嵌套的OrderedDict转换为dict,我们使用json.loads()json.dumps()方法。

  • JSON 的完整形式是 JavaScript Object Notation。这意味着由编程语言中的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过一个名为 json 的内置包支持 JSON。要使用此功能,我们在Python脚本中导入 json 包。 JSON 中的文本是通过引用字符串完成的,它包含 {} 内键值映射中的值。它类似于Python中的字典。
  • json.loads()方法可用于解析有效的 JSON字符串并将其转换为Python字典。它主要用于将 JSON 数据组成的原生字符串、字节或字节数组反序列化为Python字典。
  • json.dumps()函数将Python对象转换为 json字符串。

蟒蛇3

# import package
from collections import OrderedDict
import json
  
# define nested OrderedDict
od2 = OrderedDict([('1', 'one'), 
                   ('2', OrderedDict([('-2', 
                                       '-ive'), 
                                      ('+2', 
                                       '+ive')]))])
# convert to dict
od2 = json.loads(json.dumps(od2))
  
# display deictionary
print(type(od2))
print(od2)

输出:


{'1': 'one', '2': {'-2': '-ive', '+2': '+ive'}}