如何在for循环中处理Python字典键,同时还添加新键

时间:2020-09-17 12:10:07

标签: python python-3.x loops dictionary filter

我有一本字典,其中有多种类型的键(在本例中为keyType1和keyType2):

    example_dict = {
        "keyType2[3]": 23,
        "keyType2[-1]": -21,
        "keyType2[-2]": -22,
        "keyType1[0]": 0,
        "keyType1[2]": 2,
        "keyType1[-1].subkey1": -11,
        "keyType1[-1].subkey2": -12,
        "keyType1[-2].subkey1": -21,
        "keyType1[-2].subkey2": -22,
        "keyType1[-3]": -3,
    }

并且它们被索引,就像在列表中一样。我的任务是识别字典中索引为负的键,找到相同类型键的索引最大值,然后基于该最大值重新计算负索引。

我所拥有的:

def example_implementation(example_dict):
    negative_keys = filter(lambda x: re.search(r"\[-\d+\]", x), example_dict.keys())
    for key in negative_keys:
        indexed_key, index = re.search(r"(?P<indexed_key>.*?)\[-(?P<index>\d+)\]", key).groups()
        indexed_keys = [key for key in example_dict.keys() if indexed_key in key]
        max_index = max(
            map(lambda x: int(re.search(f"{re.escape(indexed_key)}\[([\d-]+)\]", x).group(1)), indexed_keys,)
        )
        if max_index < 0:
            # no non-negative list elements were found
            raise exceptions.KeyError
        key_mappings = filter(
            lambda x: x[0] != x[1],
            (
                map(
                    lambda x: (x, x.replace(f"{indexed_key}[-{index}]", f"{indexed_key}[{max_index + 1}]"),),
                    indexed_keys,
                )
            ),
        )
        for (old_key, new_key) in key_mappings:
            example_dict[new_key] = example_dict.pop(old_key)
    return example_dict

我的实现适用于:

    example_dict = {
        "keyType1[-1].subkey1": -11,
        "keyType1[-1].subkey2": -12,
        "keyType1[0]": 0,
        "keyType1[2]": 2,
        "keyType1[-2]": -2,
        "keyType2[3]": 3,
        "keyType2[-1]": 34,
    }

但不是

    example_dict = {
        "keyType2[3]": 23,
        "keyType2[-1]": -21,
        "keyType2[-2]": -22,
        "keyType1[0]": 0,
        "keyType1[2]": 2,
        "keyType1[-1].subkey1": -11,
        "keyType1[-1].subkey2": -12,
        "keyType1[-2].subkey1": -21,
        "keyType1[-2].subkey2": -22,
        "keyType1[-3]": -3,
    }

输出为:

{
        "keyType2[3]": 23,
        "keyType2[-2]": -22,
        "keyType1[0]": 0,
        "keyType1[2]": 2,
        "keyType2[4]": -21,
        "keyType1[3].subkey1": -11,
        "keyType1[3].subkey2": -12,
        "keyType1[4].subkey1": -21,
        "keyType1[4].subkey2": -22,
        "keyType1[5]": -3,
    }

注意第二个密钥没有得到处理。 我不知道是什么问题。有什么想法吗?

0 个答案:

没有答案