Python 2.7: 通过部分key从字典中删除一个key。

30 浏览
0 Comments

Python 2.7: 通过部分key从字典中删除一个key。

我有一个 Python 字典,其中键由元组组成,像这样:

{
 (u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Me'): 300, 
 (u'A_String_0', u'B_String_4'): 301, 
 (u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Key'): 301,
}

我想要删除字典中所有键,当键中只有部分元组出现在键中时:

例如 \'Remove_\'

在这种情况下,必须弹出两个键:一个包含 u\'Remove_Me\',另一个包含 u\'Remove_Key\'

最终,字典将看起来像这样:

{
  (u'A_String_0', u'B_String_4'): 301
}

非常感谢!

admin 更改状态以发布 2023年5月24日
0
0 Comments

由于键总是一件没有任何结构或模式的组合物,因此您始终需要完整的键才能访问字典中的元素。特别是这意味着您无法使用某些部分键找到元素。因此,为了做到这一点,除了查看所有键以外,没有其他方法:

>>> d = {
 (u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Me'): 300, 
 (u'A_String_0', u'B_String_4'): 301, 
 (u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Key'): 301}
>>> { k: v for k, v in d.items() if not any(x.startswith('Remove_') for x in k) }
{(u'A_String_0', u'B_String_4'): 301}

这将从源字典中创建一个新字典,取出每个键 k ,其中 any(x.startswith('Remove_')for x in k)不为真。如果在x中有以'Remove_'开头的元素,则any()表达式将为真。

0
0 Comments

一种方法:

    >>> d = {
     (u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Me'): 300, 
     (u'A_String_0', u'B_String_4'): 301, 
     (u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Key'): 301,
    }
    >>> 
    >>> 
    >>> d_out = {k:v for k,v in d.items() if not any(x.startswith('Remove_') for x in k)}
    >>> d_out
{(u'A_String_0', u'B_String_4'): 301}

编辑:如果您想要检查 Remove_ 是否是元组键的任何项的一部分,则最好使用以下方法:

>>> d_out = {k:v for k,v in d.items() if not any('Remove_' in x for x in k)}

0