首页 > 解决方案 > 如何在 Python 中访问子字典

问题描述

如果我想评估 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

我怎样才能获得字段的值:'Security' 和 'Position' ?

详细说明 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)

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

标签: pythondictionary

解决方案


看起来您的 dict 结构类似于:

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}

推荐阅读