简体   繁体   English

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

[英]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()

I am attempting to remove any item with "ing" in it from all keys within a dictionary, example "blowing" from the key "one" and "frying" from the key "two". 我正在尝试从字典中的所有键中删除其中带有“ ing”的任何项目,例如,从键“ one”中删除“ blowing”,从键“ two”中删除“ frying”。

The resulting dictionary would go from this: 产生的字典将来自此:

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

to this: 对此:

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

dict comprehension. 字典理解。

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

Edited to replace values ending with 'ing' with 'removed' 编辑以将“ ing”结尾的值替换为“ removed”

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

You can do this in an immutable fashion (ie, without mutating the original dict) by using a dict comprehension : 您可以通过使用dict理解以不可变的方式(即,不改变原始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']}

Try this: 尝试这个:

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

Explanation: 说明:

Start from the right, 从右边开始

  • d is the dictionary, it stores <key, [val]> d是字典,它存储<key, [val]>

  • for each key, val in d we do the following, 对于d每个key, val我们执行以下操作,

  • [ele for ele in val if not ele.lower().endswith('ing')] means for every element( ele ) in list( val ) we perform the operations : [ele for ele in val if not ele.lower().endswith('ing')]表示对于list( val )中的每个元素( ele ),我们执行以下操作:

    • convert each string to lower case 将每个字符串转换为小写
    • check if it ends-with `ing' 检查它是否以-ing结尾
    • then if none of these( if not ) then get ele 然后如果这些都不是( if not ),则得到ele
  • Then you just print { key: [ele1, ele2, ..] , .. } . 然后,您只需打印{ key: [ele1, ele2, ..] , .. }

You were trying to delete with string index not int position reference. 您试图删除的字符串索引不是int位置参考。 Here is the modified code: 这是修改后的代码:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从每个键有多个值的字典中的键中获取特定值? - How do I get a specific value from a key in a dictionary with multiple values per key? 如何删除字典中的键值? - How do I remove key values in a dictionary? Python如何从具有多个值的字典键中删除特定值? - Python how to delete a specific value from a dictionary key with multiple values? Python:如何从字典键中随机选择一个值? - Python: How do I randomly select a value from a dictionary key? 如何在python中为具有多个值的字典查找带有值的字典键? - How to find key of dictionary with from values for a dictionary with multiple values in python? 如何从字典中的字典迭代和 append 键值对并将具有相同键的值存储到列表 python - How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python Python:如何匹配键,然后将键值对值的值与另一个字典中的值相乘? - Python: How do I match keys then multiply the values of a key-value pair value with values from another dictionary? 在python中,如何找到字典中的值之和? 每个键都有多个值 - In python, how do I find the sum of values in a dictionary? Where each key has multiple values Python:获取字典中值最小但具有多个最小值的键 - Python: get key with the least value from a dictionary BUT multiple minimum values 如何从 Python 列表中删除多个(键、值)条目 - 有序字典 - How to remove multiple (key,value) entries from a Python List - Ordered Dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM