Return 不包括指定键的字典副本

Return copy of dictionary excluding specified keys

我想创建一个函数,该函数 return 是字典的副本,不包括列表中指定的键。

正在考虑这本词典:

my_dict = {
    "keyA": 1,
    "keyB": 2,
    "keyC": 3
}

without_keys(my_dict, ['keyB', 'keyC']) 的调用应该 return:

{
    "keyA": 1
}

我想用一个简洁的字典理解在一行中做到这一点,但我遇到了麻烦。我的尝试是这样的:

def without_keys(d, keys):
    return {k: d[f] if k not in keys for f in d}

这是无效的语法。我该怎么做?

你很接近,试试下面的代码片段:

>>> my_dict = {
...     "keyA": 1,
...     "keyB": 2,
...     "keyC": 3
... }
>>> invalid = {"keyA", "keyB"}
>>> def without_keys(d, keys):
...     return {x: d[x] for x in d if x not in keys}
>>> without_keys(my_dict, invalid)
{'keyC': 3}

基本上,在上述情况下,if k not in keys 将位于字典理解的末尾。

这应该适合你。

def without_keys(d, keys):
    return {k: v for k, v in d.items() if k not in keys}

在您的字典理解中,您应该遍历您的字典(不是 k ,也不确定那是什么)。例子-

return {k:v for k,v in d.items() if k not in keys}

对于那些不喜欢列表理解的人,这是我的版本:

def without_keys(d, *keys):
     return dict(filter(lambda key_value: key_value[0] not in keys, d.items()))

用法:

>>> d={1:3, 5:7, 9:11, 13:15}
>>> without_keys(d, 1, 5, 9)
{13: 15}
>>> without_keys(d, 13)
{1: 3, 5: 7, 9: 11}
>>> without_keys(d, *[5, 7])
{1: 3, 13: 15, 9: 11}

更短。显然 python 3 可以让你从 dict_keys.

'subtract' 一个 list
def without_keys(d, keys):
    return {k: d[k] for k in d.keys() - keys}

您可以将此概括为嵌套字典解决方案

def copy_dict(data, strip_values=False, remove_keys=[]):
    if type(data) is dict:
        out = {}
        for key, value in data.items():
            if key not in remove_keys:
                out[key] = copy_dict(value, strip_values=strip_values, remove_keys=remove_keys)
        return out
    else:
        return [] if strip_values else data

此递归解决方案适用于嵌套字典并从整个嵌套结构中删除不需要的键。它还使您能够 return 只有键而没有值的嵌套。

你的专线

my_dict = {"keyA": 1, "keyB": 2, "keyC": 3}
(lambda keyB, keyC, **kw: kw)(**my_dict)

其中 returns {'keyA': 1}。 不是很 pythonic 和动态,但 hacky 和短。 它使用函数参数的字典解包(解构赋值)。

另请参阅 .