在字典中,如何从具有多个值的键中删除一个值? Python

within a dictionary, how do I remove a value from a key with multiple values? Python

from collections import OrderedDict

def main():
    dictionary = OrderedDict()
    dictionary["one"] = ["hello", "blowing"]
    dictionary["two"] = ["frying", "goodbye"]

    for key in dictionary:
        print key, dictionary[key]

    user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N")
    if user_input == ("y"):
        print ""
        for key in dictionary:
            for x in dictionary[key]:
                if ("ING") in x or ("ing") in x:
                    del dictionary[key][x]

    print ""

    for key in dictionary:
        print key, dictionary[key]

main()

我正在尝试从字典中的所有键中删除任何包含 "ing" 的项目,例如 "blowing" 来自键 "one" 和 "frying" 来自键"two".

生成的字典将来自:

one ['hello', 'blowing'], two ['frying', 'goodbye']

对此:

one ['hello'], two ['goodbye']

您可以使用 dict comprehension:

>>> d = {'one': ['hello', 'blowing'], 'two': ['frying', 'goodbye']}
>>> {k: [w for w in v if not w.lower().endswith('ing')] for k, v in d.items()}
{'one': ['hello'], 'two': ['goodbye']}

您尝试使用字符串索引而不是 int 位置引用进行删除。这是修改后的代码:

from collections import OrderedDict

def main():
    dictionary = OrderedDict()
    dictionary["one"] = ["hello", "blowing"]
    dictionary["two"] = ["frying", "goodbye"]

    for key in dictionary:
        print key, dictionary[key]

    user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N")
    if user_input == ("y"):
        print ""
        for key,value in dictionary.iteritems():
            for i,x  in enumerate(value):
                if ("ING") in x or ("ing") in x:
                    del dictionary[key][i]

    print ""

    for key in dictionary:
        print key, dictionary[key]

main()

试试这个:

>>> collections.OrderedDict({key:filter(lambda x:not x.endswith('ing'), value) for key,value in dictionary.items()})
OrderedDict([('two', ['goodbye']), ('one', ['hello'])])

听写理解。

return {x : [i for i in dictionary[x] if not i.lower().endswith('ing')] for x in dictionary}

编辑以将以 'ing' 结尾的值替换为 'removed'

return {x : [i if not i.lower().endswith('ing') else 'removed' for i in dictionary[x]] for x in dictionary}
{key: [ele for ele in val if not ele.lower().endswith('ing')] for key, val in d.items()}

解释:

从右边开始,

  • d是字典,它存储<key, [val]>

  • 对于 d 中的每个 key, val,我们执行以下操作,

  • [ele for ele in val if not ele.lower().endswith('ing')] 表示对列表(val) 中的每个元素(ele) 我们执行以下操作:

    • 将每个字符串转换为小写
    • 检查它是否以 `ing' 结尾
    • 然后如果 none 个(if not)然后得到 ele
  • 然后你就打印{ key: [ele1, ele2, ..] , .. }.