代码之家  ›  专栏  ›  技术社区  ›  mpen

过滤dict只包含某些键?

  •  357
  • mpen  · 技术社区  · 15 年前

    我有一个 dict 有一大堆的条目。我只对其中的几个感兴趣。有没有一个简单的方法把其他的都删掉?

    11 回复  |  直到 7 年前
        1
  •  783
  •   Community CDub    12 年前

    构建新的dict:

    dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
    

    如果您使用的版本中缺少它们(即python2.6和更早版本),请使用它 dict((your_key, old_dict[your_key]) for ...) . 这是一样的,虽然更丑。

    请注意,与jnnnn的版本不同,它具有稳定的性能(仅取决于\u键的数量) old_dict 任何尺寸的。无论是速度还是记忆力。因为这是一个生成器表达式,所以它一次处理一个项目,并且不会查看旧目录的所有项目。

    unwanted = set(keys) - set(your_dict)
    for unwanted_key in unwanted: del your_dict[unwanted_key]
    
        2
  •  184
  •   ransford    11 年前

    略为优雅的听写理解:

    foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
    
        3
  •  67
  •   jnnnnn    15 年前

    >>> a = {1:1, 2:2, 3:3}
    >>> dict((key,value) for key, value in a.iteritems() if key == 1)
    {1: 1}
    

    if 声明。

    如果您只想选择非常多的几个键,则此方法比delnan的答案慢。

        4
  •  26
  •   Suor    8 年前

    你可以用它来做 project 来自我的函数 funcy 图书馆:

    from funcy import project
    small_dict = project(big_dict, keys)
    

    还可以看看 select_keys

        5
  •  24
  •   Y.Y    8 年前

    代码1:

    dict = { key: key * 10 for key in range(0, 100) }
    d1 = {}
    for key, value in dict.items():
        if key % 2 == 0:
            d1[key] = value
    

    代码2:

    dict = { key: key * 10 for key in range(0, 100) }
    d2 = {key: value for key, value in dict.items() if key % 2 == 0}
    

    代码3:

    dict = { key: key * 10 for key in range(0, 100) }
    d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}
    

    enter image description here

        6
  •  22
  •   Jim vartec    7 年前

    这一行lambda应该工作:

    dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
    

    举个例子:

    my_dict = {"a":1,"b":2,"c":3,"d":4}
    wanted_keys = ("c","d")
    
    # run it
    In [10]: dictfilt(my_dict, wanted_keys)
    Out[10]: {'c': 3, 'd': 4}
    

    它是一个基本的列表,遍历dict键(x中的i),如果键位于所需的键列表(y)中,则输出一个元组(键,值)对列表。dict()将整个对象包装为dict对象输出。

        7
  •  15
  •   Kai    15 年前

    给你原来的字典 orig 以及你感兴趣的一组条目 keys :

    filtered = dict(zip(keys, [orig[k] for k in keys]))
    

    这并不像delnan的答案那么好,但应该适用于所有感兴趣的Python版本。然而,它对生命的每一个元素都是脆弱的 存在于原始词典中。

        8
  •  10
  •   MyGGaN    12 年前

    如果你想要的钥匙不在旧字典里怎么办?delnan解决方案将抛出您可以捕获的KeyError异常。如果这不是你需要的也许你想:

    1. 只包括在旧目录和你想要的一组密钥中同时存在的密钥。

      old_dict = {'name':"Foobar", 'baz':42}
      wanted_keys = ['name', 'age']
      new_dict = {k: old_dict[k] for k in set(wanted_keys) & set(old_dict.keys())}
      
      >>> new_dict
      {'name': 'Foobar'}
      
    2. default = None
      new_dict = {k: old_dict[k] if k in old_dict else default for k in wanted_keys}
      
      >>> new_dict
      {'age': None, 'name': 'Foobar'}
      
        9
  •  8
  •   Ryan Shea    10 年前

    此函数将执行以下操作:

    def include_keys(dictionary, keys):
        """Filters a dict by only including certain keys."""
        key_set = set(keys) & set(dictionary.keys())
        return {key: dictionary[key] for key in key_set}
    

    就像delnan的版本一样,这个版本使用字典理解,并且对于大型字典有稳定的性能(仅取决于您允许的键的数量,而不是字典中的键的总数)。

    就像MyGGan的版本一样,这个版本允许您的键列表包含字典中可能不存在的键。

    作为奖励,这里是相反的,您可以通过排除原始中的某些键来创建字典:

    def exclude_keys(dictionary, keys):
        """Filters a dict by excluding certain keys."""
        key_set = set(dictionary.keys()) - set(keys)
        return {key: dictionary[key] for key in key_set}
    

    请注意,与delnan的版本不同,该操作没有执行到位,因此性能与字典中的键数有关。但是,这样做的好处是函数不会修改提供的字典。

    添加了一个单独的函数,用于从dict中排除某些键。

        10
  •  6
  •   marsl    7 年前

    另一种选择:

    content = dict(k1='foo', k2='nope', k3='bar')
    selection = ['k1', 'k3']
    filtered = filter(lambda i: i[0] in selection, content.items())
    

    但你得到了一个 list (Python2)或由返回的迭代器(Python3) filter() dict .

        11
  •  6
  •   this.srivastava    6 年前

    如果我们想在删除选定键的情况下创建一个新词典,我们可以利用词典理解

    d = {
    'a' : 1,
    'b' : 2,
    'c' : 3
    }
    x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
    y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
    # x is {'a': 1, 'b': 2}
    # y is {'a': 1, 'b': 2}
    
        12
  •  3
  •   Georgy rassa45    5 年前

    你可以用 python-benedict

    安装: pip install python-benedict

    from benedict import benedict
    
    dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])
    

    它在GitHub上是开源的: https://github.com/fabiocaccamo/python-benedict


        13
  •  1
  •   nehem    8 年前

    缩写:

    [s.pop(k) for k in list(s.keys()) if k not in keep]
    

    正如大多数答案所暗示的那样,为了保持简洁性,我们必须创建一个重复的对象 list dict . 这一个创造了一个扔掉 但删除了原始文件中的密钥 口述 .

        14
  •  0
  •   Nouman ProfHase85    6 年前

    下面是另一个使用 del 一行:

    for key in e_keys: del your_dict[key]
    

    e_keys 要排除的密钥列表。它会更新你的字典而不是给你一个新的。

    new_dict = your_dict.copy()           #Making copy of dict
    
    for key in e_keys: del new_dict[key]
    
        15
  •  0
  •   Sachin    5 年前

    我们可以简单地使用lambda函数,如下所示:

    >>> dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
    >>> large_dict = {"a":1,"b":2,"c":3,"d":4}
    >>> new_dict_keys = ("c","d")
    >>> small_dict=dict_filter(large_dict, new_dict_keys)
    >>> print(small_dict)
    {'c': 3, 'd': 4}
    >>>