【问题标题】:how do i convert nested dictionary within a dictionary to dictionary如何将字典中的嵌套字典转换为字典
【发布时间】:2021-08-06 13:20:56
【问题描述】:

我有一本字典如下:

nested_dict = { 'dictB': {'dictA': {'key_1': 'value_1'}}}

基本上我希望键 dictB 的值作为字典。

我试过了

  1. dict(nested_dict["dictB"].values()) 但我有错误
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-104-275e88e1ed17> in <module>
----> 1 dict(nested_dict["dictB"].values())

ValueError: dictionary update sequence element #0 has length 1; 2 is required
  1. nested_dict["dictB"].values() 。我有 dict_values([{'key_1': 'value_1'}]) 本身就是一个列表,但我希望它是字典 有什么办法可以得到dictB键的字典。

【问题讨论】:

  • nested_dict["dictB"] 怎么样?

标签: python dictionary nested


【解决方案1】:

既然已经是dict了,应该可以直接得到,不用做任何转换:

dict_b = nested_dict["dictB"]

【讨论】:

    【解决方案2】:

    如果要获取分配给dictB键的值中的字典, 您可以通过访问nested_dict 字典的键值来访问它,如下所示: nested_dict['dictB']

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 2023-03-11
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多