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

2024-09-27 18:17:30 发布

您现在位置: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”的项,例如从键“one”中删除“blowing”,从键“two”中删除“frying”。在

生成的字典将来自于:

^{pr2}$

为此:

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

Tags: keyinhelloforinputdictionarymainone
3条回答
{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”结尾
    • 如果没有这些(if not),那么得到ele
  • 然后只需打印{ key: [ele1, ele2, ..] , .. }

您可以使用dict comprehension以一种不变的方式(即,不改变原始dict)执行此操作:

>>> 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']}

听写理解。在

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

已编辑以将以“ing”结尾的值替换为“removed”

^{pr2}$

相关问题 更多 >

    热门问题