python中能否将字典当做值赋给列表呢?
我在对代码做了一个简单的演示,但是为什么不行呢?还是说python就不能列表套字典,只能是字典套列表?
>>> a=[]
>>> b=0
>>> a[b]={'key':'vi'}
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a[b]={'key':'vi'}
IndexError: list assignment index out of range
>>>
This problem has nothing to do with list nesting. Normal assignment will also cause your error.
The correct approach is to use the append method of the array.
a = []
means this is an empty list. There are no elements present.
Python can assign dictionary values to list elements.
a is an empty list. Your access to a[0] is obviously out of bounds.
list assignment index out of range means that your access to array index is out of bounds.
Python knowledge points:
List data type characteristics:
1. Each element of List can be any data type of Python (Boolean, Number, String, List, Dict, Set...)
2. List cannot be accessed out of bounds, it still cannot be accessed and does not exist List element
Code analysis: