【问题标题】:Accessing value which is nested inside 2 keys访问嵌套在 2 个键中的值
【发布时间】:2017-07-27 13:50:58
【问题描述】:

假设我有以下字典:

L = {'A': {'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}, 'B': {'root[3]': 'thirdvalue', 'root[4]': 'Fourthvalue'}}

如何访问Python 2.7 中键 root[1], root[2], root[3], root[4] 的值(root[] 的索引是动态的)。

【问题讨论】:

  • L['A']['root[1]']L['B']['root[3]'] 等。如果您要问的不是那么简单,您可能需要对问题添加更多解释。

标签: python python-2.7 logic


【解决方案1】:

试试:

>>> L = {'A': {'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}, 'B': {'root[3]': 'thirdvalue', 'root[4]': 'Fourthvalue'}}
>>> L['A']['root[1]']
'firstvalue'
>>> L['A']['root[2]']
'secondvalue'
>>> L['B']['root[3]']
'thirdvalue'
>>> L['B']['root[4]']
'Fourthvalue'
>>> 

【讨论】:

    【解决方案2】:

    类似这样的:

    for (key, value) in L.items():
        for (another_key, real_value) in value.items():
            print(another_key, real_value)
    

    【讨论】:

      【解决方案3】:

      要访问嵌套在 dict 中的 dict 中的值,我使用了以下步骤:

      L = {'A': {'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}, 'B': {'root[3]': 'thirdvalue', 'root[4]': 'Fourthvalue'}}
      
      Solution:
      
      F = {}
      G = []
      F = L.get("A", None)
      F= {{'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}}
      for value in F.values():
          G.append(value)
      
      Output:
      G = ['firstvalue', 'secondvalue']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        相关资源
        最近更新 更多