Reputation: 41
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".
The resulting dictionary would go from this:
one ['hello', 'blowing'], two ['frying', 'goodbye']
to this:
one ['hello'], two ['goodbye']
Upvotes: 0
Views: 592
Reputation: 2665
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}
Upvotes: 1
Reputation: 28199
{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]>
for each key, val
in d
we do the following,
[ele for ele in val if not ele.lower().endswith('ing')]
means for every element(ele
) in list(val
) we perform the operations :
if not
) then get ele
Then you just print { key: [ele1, ele2, ..] , .. }
.
Upvotes: 1
Reputation: 19733
Try this:
>>> collections.OrderedDict({key:filter(lambda x:not x.endswith('ing'), value) for key,value in dictionary.items()})
OrderedDict([('two', ['goodbye']), ('one', ['hello'])])
Upvotes: 0
Reputation: 1563
You were trying to delete with string index not int position reference. 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()
Upvotes: -1
Reputation: 3481
You can do this in an immutable fashion (i.e., without mutating the original dict) by using a 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']}
Upvotes: 0