对Python字典/列表中不存在的键/索引赋值

4
为什么我们可以通过直接分配键值对来向字典中添加新元素,但不能对列表进行同样的操作呢?
例如:
dictl = {}
dictl['new_key'] = value
print dictl  # prints {'new_key: value}

但是,
listl = []
listl[0] = value   # IndexError: list assignment index out of range
2个回答

2
  1. 它们具有不同的内部表示和用法。

  2. 扩展列表不是一项微不足道的操作,因此不应该轻易、隐式地完成。

  3. 在扩展列表中未使用的索引位置上会放置什么?

  4. 字典不会受到这种影响,因为添加新的键值对不会产生其他副作用。


0

我成功地通过list.insert(index, item)实现了更新不存在的索引的目标。 但是请注意,如果要插入的索引大于len(list) - 1,则该项将附加到列表中。例如:

 list = []
 list[0] = 5 #indexError, but
 list.insert(0, 5) # works => list = [5]

索引 > len(list) - 1

 list = [1, 3]
 list.insert(4, 8) # => [1, 3,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接