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

5 Answers 5

1

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Ok this works nice, can you rework it instead replace that value with "removed"
Awesome! Thank you!
1
{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 :

    • convert each string to lower case
    • check if it ends-with `ing'
    • then if none of these(if not) then get ele
  • Then you just print { key: [ele1, ele2, ..] , .. }.

1 Comment

Exact duplicate of my answer ;)
0

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

2 Comments

can you explain what this does?
{k: ... for k, v in d.items()} is a dict comprehension, it creates dict with the same keys but altered values. For each key k and value v we iterate over all words w in v, create a new list that contains all such w that their lowered version doesn't end with "ing", and then use this list as a new value in the new dict.
0

Try this:

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

Comments

-1

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

2 Comments

This won't work if there are multiple -ing in one list.
Oh yes, it wont work fine in that case. User has asked query regarding the shared code , hence it is only meant for tat. so, that he/she can get a understanding of what was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.