ayuLiao
6/6/2018 - 3:35 AM

python实现字典切片

在python中字典是无法使用切片的,自定义一个方法,用于实现字典切片


#先取出所有 keys,再对 keys 切片,然后用得到的键去字典里找值重新创建一个新的字典
def dict_slice(adict, start, end):
    keys = adict.keys()
    dict_slice = {}
    for k in keys[start:end]:
        dict_slice[k] = adict[k]
    return dict_slice
    
    
#更优雅的版本
dict_slice = lambda adict, start, end: dict((k, adict[k]) for k in adict.keys()[start:end])

#如果是 python 2.7 及以上的版本,还可以用 dict comprehension 来替换 dict() 函数
dict_slice = lambda adict, start, end: { k:adict[k] for k in adict.keys()[start:end] }

```
使用一下
```
In [17]: d = {}.fromkeys(range(10), 5)

In [18]: d
Out[18]: {0: 5, 1: 5, 2: 5, 3: 5, 4: 5, 5: 5, 6: 5, 7: 5, 8: 5, 9: 5}

In [19]: slice = dict_slice(d, 3, 5)

In [20]: type(slice)
Out[20]: dict

In [21]: slice
Out[21]: {3: 5, 4: 5}