如果我想评估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)
我的目标是将位置和安全性放入数据框中
看起来您的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}
我已经尝试过并能够解析所需的。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'
如果不是答: