首页 > 解决方案 > Python:如何使用列表中的步骤索引更新字典

问题描述

我是一个一周大的 Python 学习者。我想知道:假设:

list= [“a”, “A”, “b”, “B”, “c”, “C”]

我需要在字典中更新它们以获得如下结果:

dict={“a”:”A”, “b”:”B”, “c”:”C”}

我尝试在dict.update({list[n::2]: list[n+1::2]}and中使用列表索引for n in range(0,(len(list)/2))

我想我做错了什么。请纠正我。

先感谢您。

标签: pythonlistdictionaryindexing

解决方案


尝试以下操作:

>>> lst = ['a', 'A', 'b', 'B', 'c', 'C']
>>> dct = dict(zip(lst[::2],lst[1::2]))
>>> dct
{'a': 'A', 'b': 'B', 'c': 'C'}

说明

>>> lst[::2]
['a', 'b', 'c']
>>> lst[1::2]
['A', 'B', 'C']
>>> zip(lst[::2], lst[1::2])
# this actually gives a zip iterator which contains:
# [('a', 'A'), ('b', 'B'), ('c', 'C')]
>>> dict(zip(lst[::2], lst[1::2]))
# here each tuple is interpreted as key value pair, so finally you get:
{'a': 'A', 'b': 'B', 'c': 'C'}

注意:不要将变量命名为与 python 关键字相同的名称。

您的程序的正确版本是:

lst = ['a', 'A', 'b', 'B', 'c', 'C']
dct = {}
for n in range(0,int(len(lst)/2)):
  dct.update({lst[n]: lst[n+1]})
print(dct)

您的不起作用,因为您在每次迭代中都使用了切片,而不是访问每个单独的元素。lst[0::2]['a', 'b', 'c']lst[1::2]['A', 'B', 'C']。因此,对于第一次迭代,当n == 0您尝试使用该对更新字典时['a', 'b', 'c'] : ['A', 'B', 'C'],您将收到类型错误,因为list无法将其分配为字典的键,因为lists 是不可散列的。


推荐阅读