Slicing a dictionary

后端 未结 6 911
后悔当初
后悔当初 2020-12-02 10:28

I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:

# the dictionary
d = {1:         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 10:59

    On Python 3 you can use the itertools islice to slice the dict.items() iterator

    import itertools
    
    d = {1: 2, 3: 4, 5: 6}
    
    dict(itertools.islice(d.items(), 2))
    
    {1: 2, 3: 4}
    

    Note: this solution does not take into account specific keys. It slices by internal ordering of d, which in Python 3.7+ is guaranteed to be insertion-ordered.

提交回复
热议问题