在python中将zip对象映射到字典时的KeyError

时间:2018-03-10 11:58:38

标签: python dictionary

知道我在一个场景中不断获得KeyError异常有点奇怪。我在两个字符串序列上尝试了zip,然后在dict函数中使用了该对象。但是,当我尝试索引这个序列时,我一直得到KeyError。

>>> rawdata = "acbd"
>>> l1 = "abcd"
>>> l2 = "cdef"
>>> zp1 = zip(l1, l2)
>>> type(zp1)
<class 'zip'>
>>> # zp1 is basically used for mapping. So every character in l1 is mapped to l2. So this would be
... # used to alter the rawdata object. Meaning every char in raw data would basically act as a key
... # to the below dictionary object and return a value which is then used in the join function.
...
>>> newstring = ''
>>> newstring = ''.join([dict(zp1)[x] for x in rawdata])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
KeyError: 'c'

有趣的是,如果我不使用zp1对象,而不是直接在dict中使用zip(l1,l2),则相同的代码正常工作。为什么会这样?有线索吗? 以下是运行良好的代码。

>>> rawdata = "acbd"
>>> l1 = "abcd"
>>> l2 = "cdef"
>>> newstring = ''.join([dict(zip(l1, l2))[x] for x in rawdata])
>>> print(newstring) # Working as expected, without any exception
cedf

0 个答案:

没有答案