Slicing a dictionary

后端 未结 6 896
后悔当初
后悔当初 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 11:18

    set intersection and dict comprehension can be used here

    # the dictionary
    d = {1:2, 3:4, 5:6, 7:8}
    
    # the subset of keys I'm interested in
    l = (1,5)
    
    >>>{key:d[key] for key in set(l) & set(d)}
    {1: 2, 5: 6}
    

提交回复
热议问题