【问题标题】:deleting specific dictionary items in python (based on key format)删除python中的特定字典项(基于键格式)
【发布时间】:2021-12-22 21:01:01
【问题描述】:

我有一个由键值对组成的 python 字典。我想要做的是删除键是某种格式的项目。 在我的情况下,我要删除的键格式是:字母、数字、数字。 示例:A12、A56、A32

所以在下面的例子中,我想删除所有由 Axx 组成的项目(其中 x 是数字)。

{'A34': 83, 'B32': 70, 'A44': 66, A12: 47, 'B90': 71}

我知道可以使用正则表达式来定位格式。 例如下面的代码将计算具有 Axx 格式的键的数量(其中 x 是数字)

print(sum(1 for k in d.keys() if re.match('^A\\d{2}$', k)))

但是我怎样才能改变它,以便它可以删除字典 whos 键是 Axx 格式的项目。

【问题讨论】:

    标签: python python-3.x regex dictionary


    【解决方案1】:

    您可以使用字典理解:

    dct = {'A34': 83, 'B32': 70, 'A44': 66, 'A12': 47, 'B90': 71}
    dct = {k:v for k,v in dct.items() if not re.fullmatch(r'A\d{2}', k) }
    

    if not re.fullmatch(r'A\d{2}', k) 条件过滤掉(删除)任何具有完全匹配 A<two digits> 模式的键的项目(请注意,re.fullmatch 需要完整的字符串匹配,因此不需要锚点)。

    【讨论】:

    • 非常感谢它完美运行
    【解决方案2】:
    for key in dictionary:
        if condition(key):
            del dictionary[key]
    
    # Adapted to your code
    temp = dictionary.copy()
    for k in dictionary:
        if re.fullmatch(r'A\d{2}', k):
            del temp[k]
    dictionary = temp
    

    【讨论】:

    • 不应删除 for 循环中的项目。
    • @j1-lee for循环使用了生成器,这意味着它不会影响del,尤其是字典的key
    • 那为什么我看到RuntimeError: dictionary changed size during iteration
    • @j1-lee Np。所做的更改
    • 必须就地修改...嗯
    【解决方案3】:

    您可以使用popdel 删除匹配项。为了避免在迭代字典时修改字典,您可以迭代字典键

    d = {'A34': 83, 'B32': 70, 'A44': 66, 'A12': 47, 'B90': 71}
    for k in list(d.keys()):
        if re.match('^A\\d{2}$', k):
            d.pop(k) # del d[k]
    print(d) # {'B32': 70, 'B90': 71}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2016-07-03
      • 2014-09-02
      • 2023-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多