删除循环内的特定字典值

时间:2018-05-15 13:32:32

标签: python dictionary context-free-grammar

我正在尝试制作一个无上下文的语法简化软件。 当我从字典的值甚至键值对中删除一些特定的项目时,我感到困惑。

问题在于它不遵循模式。

  • 如果元素属于V1,我需要将其保存在字典中。 (V1是推导终端的所有值的列表,这些人是我需要保留在字典上的唯一值,但事情并非那么简单)

  • 如果元素不属于V1且字典的值是字符串,我需要删除该元素。

  • 如果元素不属于V1且字典的值是列表,我需要检查它是否是该列表的单个元素,如果是,则删除值。

失败的循环在这里。 我打印了部分,我无法弄清楚修改字典的逻辑。

counter = 0
for k,v in derivations.items():
    derivationsCount = len(v)

    while counter < derivationsCount:
        if lista_ou_string(v[counter]): # returns True for lists, False for else
            sizeOfList = len(v[counter])
            counter2 = 0

            while counter2 <= (sizeOfList - 1):
                if v[counter][counter2] not in V1:
                    if derivationsCount == 1:
                        print("# NEED TO DELETE BOTH KEY AND VALUE FROM derivatios.items()")
                    else:
                        print("# NEED TO DELETE ONLY THE VALUE FROM derivations.items()")
                counter2 += 1

        else: # strings \/
            if v[counter] not in V1:
                if derivationsCount == 1:
                    print("# NEED TO DELETE BOTH KEY AND VALUE FROM derivatios.items()")
                else:
                    print("# NEED TO DELETE ONLY THE VALUE FROM derivations.items()")
            else:
                print("# DO NOT DELETE ANYTHING! ALL LISTS ELEMENTS BELONGS TO 'V1'")
        counter += 1

2 个答案:

答案 0 :(得分:0)

如果要从字典中删除键值对,请使用del

>>> my_dictionary = {'foo':'bar', 'boo':'baz'}
>>> del my_dictionary['foo']
>>> my_dictionary
{'boo': 'baz'}

如果您要删除该值,但保留该密钥,则可以尝试分配密钥None

>>> my_dictionary = {'foo':'bar', 'boo':'baz'}
>>> my_dictionary['foo'] = None
>>> my_dictionary
{'foo': None, 'boo': 'baz'}

答案 1 :(得分:0)

人们不希望在循环时修改字典(或列表)。因此,我创建了derivations - new_derivations的副本并修改了此new_derivations

import copy
new_derivations = copy.deepcopy(derivations)
for k, v in derivations.items():
    for vi in v:
        if (lista_ou_string(vi) and not set(vi).issubset(V1)) or vi not in V1:
            if len(v) == 1:
                # NEED TO DELETE BOTH KEY AND VALUE FROM derivatios.items()
                del new_derivations[k]
                break
            else:
                # NEED TO DELETE ONLY THE VALUE FROM derivations.items()
                idx = new_derivations[k].index(vi)
                del new_derivations[k][idx]

我实际上会以不同的方式实现上述代码:而不是考虑从derivations中删除项目,而不是考虑将元素添加到列表中。然后代码变得更加简单:

new_derivations = {}
for k, v in derivations.items():
    nv = [vi for vi in v if ((isinstance(vi, list) and set(vi).issubset(V1))
                             or vi in V1)]
    if nv:
        new_derivations[k] = nv