python - 如何在 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)
我的目标是将位置和安全性放入数据框
解决方案
看起来您的 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}
推荐阅读
- php - “返回类型在可迭代类型数组中没有指定值类型。” 错误不反映现实?
- r - 是否可以将考试结果更改为不同的等级?
- javascript - 在 Javascript 中创建复制按钮
- json - 使用 JQ 将纯文本块转换为 JSON
- python - MQTT 服务器失败
- python - 每当我单击键盘上的特定键时,如何播放音频?
- r - 测试互联网是否通过WiFi或R中的以太网电缆连接
- python-3.x - 找不到 Python os 模块显示的文件夹存在
- ktor - 如何使用 Ktor Oauth 刷新令牌?
- c++ - 我会很感激帮助将 ints/floats 转换为 c++ 中的字符串