Python - intersection between a list and keys of a dictionary

后端 未结 6 1578
耶瑟儿~
耶瑟儿~ 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: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'}}
    

提交回复
热议问题