>>> d = {'year':[{'season':['winter',['spring']]}]}
>>> d['year']['season']['winter']
Traceback (most recent call last):
File "<python-input-2>", line 2, in <module>
d['year']['season']['winter']
~~~~~~~~~^^^^^^^^^^
TypeError: list indices must be integers or slices, not str
我尝试更改变量的名称,但没有任何作用。我需要做什么才能“拔出”“弹簧”?
键
year
的值是一个列表,所以需要对列表进行索引。 一步一步来吧:
>>> d = {'year':[{'season':['winter',['spring']]}]}
>>> d['year'] # result is list
[{'season': ['winter', ['spring']]}]
>>> d['year'][0] # result is dict
{'season': ['winter', ['spring']]}
>>> d['year'][0]['season'] # result is list
['winter', ['spring']]
>>> d['year'][0]['season'][1] # result is another list
['spring']
>>> d['year'][0]['season'][1][0] # result is string
'spring'