如何在Python中访问子主题

时间:2019-02-28 09:44:54

标签: python dictionary

如果我想评估pycharm上的代码片段,我将具有以下内容:

fieldData['PORTFOLIO_MPOSITION']
>>> {'PORTFOLIO_MPOSITION': {'Security': 'OPTYWHKS Curncy', 'Position': 1.0}}

但是,如果我尝试:

fieldData['PORTFOLIO_MPOSITION']['Security']

我收到以下错误:

>>> {TypeError}list indices must be integers or slices, not str

如何获取“安全”和“位置”字段的值?

在下面的循环中进一步详细说明fieldfata;

                if (fld in fieldData) and isinstance(fieldData[fld], list):
                    if (fld =='PORTFOLIO_MPOSITION'):
                        val =  fieldData['PORTFOLIO_MPOSITION']
                        datum =[ticker,fld,val ]
                        datum.extend(corrtype(fieldData['PORTFOLIO_MPOSITION'])Id)
                        data.append(datum)

我的目标是将位置和安全性放入数据框

2 个答案:

答案 0 :(得分:0)

您的字典结构看起来像:

fieldData['PORTFOLIO_MPOSITION'] = 
    {'PORTFOLIO_MPOSITION' : {'Security': 'OPTYWHKS Curncy', 'Position': 1.0}}

在这种情况下,您将需要访问“安全性”,例如:

fieldData['PORTFOLIO_MPOSITION']['PORTFOLIO_MPOSITION']['Security']

要能够使用fieldData ['PORTFOLIO_MPOSITION'] ['Security']访问它,当您在控制台上输入fieldData ['PORTFOLIO_MPOSITION']时,其外观应类似于:

 {'Security': 'OPTYWHKS Curncy', 'Position': 1.0}

答案 1 :(得分:-1)

我已经尝试过并能够解析所需的内容。 PFB:

In [1]: a = {
        "PORTFOLIO_MPOSITION":
        {
            "Security": "OPTYWHKS Curncy",
            "Position": 1.0
        }
   }

    In [2]: a
    Out[2]: {'PORTFOLIO_MPOSITION': {'Security': 'OPTYWHKS Curncy', 'Position': 1.0}}

    In [3]: a['PORTFOLIO_MPOSITION']
    Out[3]: {'Security': 'OPTYWHKS Curncy', 'Position': 1.0}

    In [4]: a['PORTFOLIO_MPOSITION']['Security']
    Out[4]: 'OPTYWHKS Curncy'

如果不是答案,您能再简单介绍一下问题吗