如果我想在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)
我的目标是将位置和安全性放入Dataframe中
看起来你的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}
我已经尝试过并能够解析所需的内容。 PFD:
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'
如果不是答案的话,你能不能再问一下这个问题