如何在交互式shell中访问字典的字典

2024-06-22 10:44:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据:

>>> {'Foo':{'LG.ip': {'NKCells': 3.4439999999999995, 'DendriticCells': 8.3127499999999994, 'Macrophages': 12.146249999999998}}}

但为什么访问以下方式会产生错误:

>>> dict['Foo']['LG.ip']['NKCells']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Foo'

正确的方法是什么?你知道吗


Tags: 数据ipmostfoo错误方式calldict
2条回答

你没有将字典保存到变量中!因此,您没有可以访问哪些密钥的变量。你知道吗

In [2]: a={'Foo':{'LG.ip': {'NKCells': 3.4439999999999995, 'DendriticCells': 8.3127499999999994, 'Macrophages': 12.146249999999998}}}

In [3]: a['Foo']['LG.ip']['NKCells']
Out[3]: 3.4439999999999995

正如张善臣所说: 当您尝试dict['key']时,您可以访问最原始的Python字典中的键,它是所有字典的父类。你知道吗

在交互式解释器(仅限于)中,可以使用the special identifier ^{},它存储上一次求值的结果:

>>> {'Foo':{'LG.ip': {'NKCells': 3.4439999999999995, 'DendriticCells': 8.3127499999999994, 'Macrophages': 12.146249999999998}}}
{'Foo': {'LG.ip': {'NKCells': 3.4439999999999995, 'DendriticCells': 8.31275, 'Macrophages': 12.146249999999998}}}
>>> _['Foo']['LG.ip']['NKCells']
3.4439999999999995

相关问题 更多 >