Python - intersection between a list and keys of a dictionary

后端 未结 6 1659
耶瑟儿~
耶瑟儿~ 2021-01-04 00:33

I have a list that looks like this:

l1 = [\'200:200\', \'90:728\']

I have a dictionary that looks like this:

d1 = {\'200:20         


        
6条回答
  •  余生分开走
    2021-01-04 01:22

    You can use a list comprehension in the dict constructor:

    result = dict([(k,d1[k]) for k in l1 if k in d1])
    

    If you're worried about removing duplicate keys, make l1 into a set first:

    result = dict([(k,d1[k]) for k in set(l1) if k in d1])
    

提交回复
热议问题