Slicing a dictionary

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

    the dictionary

    d = {1:2, 3:4, 5:6, 7:8}
    

    the subset of keys I'm interested in

    l = (1,5)
    

    answer

    {key: d[key] for key in l}
    

提交回复
热议问题