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

时间:2016-05-28 18:14:50

标签: python dictionary key

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 ['hello', 'blowing'], two ['frying', 'goodbye']

到此:

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

5 个答案:

答案 0 :(得分:1)

dict comprehension。

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}

答案 1 :(得分:0)

您可以使用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']}

答案 2 :(得分:0)

试试这个:

Respect\Validation\Rules\Email

答案 3 :(得分:0)

{key: [ele for ele in val if not ele.lower().endswith('ing')] for key, val in d.items()}

<强>解释

从右边开始,

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

  • key, val中的d我们执行以下操作,

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

    • 将每个字符串转换为小写
    • 用`ing'
    • 检查它是否结束
    • 然后如果这些(if not)都没有得到ele
  • 然后您只需打印{ key: [ele1, ele2, ..] , .. }

答案 4 :(得分:-1)

您试图使用字符串索引删除而不是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()