Python - intersection between a list and keys of a dictionary

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

    Define efficient. Anyway here's what I would do. If it was too slow I'd probably move it to Cython.

    s1 = set(l1)
    s2 = set(d1.keys())
    s3 = s1 & s2
    # now you can access d1 using only keys in s3, or construct a new dict if you like
    d2 = dict([(k,d1[k]) for k in s3])
    
    0 讨论(0)
  • 2021-01-04 01:18

    In 3.x, this can be as simple as:

    >>> {k: d1[k] for k in (d1.keys() & l1)}
    {'200:200': {'foo': 'bar'}}
    

    Under 2.7, you can use dict.viewkeys() to recreate this functionality:

    >>> {k: d1[k] for k in (d1.viewkeys() & l1)}
    {'200:200': {'foo': 'bar'}}
    

    Under older versions of 2.x, it's a tad more verbose:

    >>> {k: d1[k] for k in (set(d1).intersection(l1))}
    {'200:200': {'foo': 'bar'}}
    
    0 讨论(0)
  • 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])
    
    0 讨论(0)
  • 2021-01-04 01:23

    Not sure about each solution performance, but I would do:

    {k: v for k, v in d1.items() if k in l1}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 01:30

    You can use the following code:

    keys = set(l1).intersection(set(d1.keys()))
    result = {k:d1[k] for k in keys}
    

    EDIT: As commenters suggest you can replace the first line with, in Python 2.x:

    keys = set(l1).intersection(d1)
    

    And in Python 3.x:

    keys = d1.keys() & l1
    
    0 讨论(0)
提交回复
热议问题