insert()方法中的字典推导不工作



我正在制作一个MappingList类,这是一个作为OrderedDict实现的列表。

这是MappingList类(省略了一些方法):

class MappingList(MutableSequence):
"""
A MappingList is a regular list implemented as a dictionary
"""
def __repr__(self):
return str(list(self.seq.values()))
def __getitem__(self, item):
try:
return self.seq[item]
except KeyError:
_traceback_from_none(IndexError, "list index out of range")
def __setitem__(self, key, value, *, usage=None):
if key > max(self.seq.keys()) and usage != "append":
raise IndexError("list index out of range")
self.seq[key] = value
def __delitem__(self, key):
try:
del self.seq[key]
except KeyError:
_traceback_from_none(IndexError, "list index out of range")
def __len__(self):
return len(self.seq)
def __eq__(self, other):
if not isinstance(other, MappingList):
return NotImplemented
return self.seq == other.seq
@classmethod
def _dict_from_seq(cls, seq):
return OrderedDict(enumerate(seq))
def _next_available_slot(self):
return max(self.seq) + 1
def insert(self, index, value):  # todo: insert() should not overwrite
"""Insert a value into the MappingList"""
if index > max(self.seq.keys()):
raise IndexError("list index out of range")
for k, v in {k: v for k, v in self.seq.items() if k > index}:
del self.seq[k]
self.seq[k + 1] = v
self[index] = value

当我尝试将项目插入MappingList时,我得到以下错误:

File "C:...My Python Programsfree_timemappinglist.py", line 103, in test_insert
self.li.insert(1, MappingList(["blah", 1, 5.8]))
File "C:...My Python Programsfree_timemappinglist.py", line 85, in insert
for k, v in {k: v for k, v in self.seq.items() if k > index}:
TypeError: cannot unpack non-iterable int object

为什么会出现这个错误?OrderedDict.items()返回一个整数吗?

错误不会因此发生

当不提供keys(), values(), items()时,python默认遍历键。您需要提供items()来告诉python获取键和值。

for k, v in {k: v for k, v in self.seq.items() if k > index}.items(): 

相关内容

  • 没有找到相关文章

最新更新