Python - intersection between a list and keys of a dictionary

后端 未结 6 1651
耶瑟儿~
耶瑟儿~ 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:24

    If memory allocation and deallocation is making this process take too long, itertools to the rescue.

    import itertools
    result = {dict_key:d1[dict_key] for dict_key in itertools.ifilter(lambda list_item: list_item in d1, l1) }
    

    This doesn't unnecessarily allocate memory for a whole new collection, and l1 could easily be an iterator instead of a list.

提交回复
热议问题