user6240030 user6240030 - 1 year ago 38
Python Question

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]


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".

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'

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