在 Python 中,我们知道字典没有切片。我该怎么做?
这是我的代码:
def my_dict_slice(dict, start, end, step=None):
new_dict = {}
if not step:
step = 1
step_continue = step
index = start
index_continue = 0
for idx, item in enumerate(dict.items()):
if index != 0 and index_continue != start:
index_continue += 1
continue
if start <= index < end:
if step != 1:
if step_continue == step:
new_dict[item[0]] = item[1]
index += step
step_continue = 1
else:
step_continue += 1
continue
else:
new_dict[item[0]] = item[1]
index += step
return new_dict
我找到了一个很好的解决方案:
dict(list(my_dict.items())[start:end:step])