删除循环中的特定字典值

2024-04-23 06:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个上下文无关的语法简化软件。 当涉及到从字典的值甚至键值对中删除某些特定的项时,我会感到困惑。你知道吗

问题是它没有遵循一种模式。你知道吗

  • 如果元素属于V1,我需要将它保存在字典中。 (V1是派生终端的所有值的列表,我只需要在字典中保留这些值,但没那么简单)

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

  • 如果元素不属于V1并且dictionary的值是一个列表,我需要检查它是否是该列表中的单个元素,如果是,请删除Value。

失败的循环在下面。 我把修改词典时弄不懂逻辑的部分打印出来了。你知道吗

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

Tags: tofrom元素if字典valuecounteritems
2条回答

人们不想在循环浏览字典(或列表)时对其进行修改。因此,我创建了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

如果要从字典中删除键、值对,请使用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'}

相关问题 更多 >