user6359012 user6359012 - 1 year ago 71
Python Question

How to remove a dict objects(letter) that remain in another str?

Suppose I have this dictionary:

x = {'a':2, 'b':5, 'g':7, 'a':3, 'h':8}`

And this input string:

y = 'agb'

I want to delete the keys of
that appear in
, such as, if my input is as above, output should be:

{'h':8, 'a':3}

My current code is here:

def x_remove(x,word):
x1 = x.copy() # copy the input dict
for i in word: # iterate all the letters in str
if i in x1.keys():
del x1[i]
return x1

But when the code runs, it removes all existing key similar as letters in word. But i want though there is many keys similar as letter in word , it only delete one key not every

wheres my wrong, i got that maybe but Just explain me how can i do that without using del function

Answer Source

You're close, but try this instead:

def x_remove(input_dict, word):
    output_dict = input_dict.copy()

    for letter in word:        
        if letter in output_dict:
            del output_dict[letter]

    return output_dict

For example:

In [10]: x_remove({'a': 1, 'b': 2, 'c':3}, 'ac')
Out[10]: {'b': 2}

One problem was your indentation. Indentation matters in Python, and is used the way { and } and ; are in other languages. Another is the way you were checking to see if each letter was in the list; you want if letter in output_dict since in on a dict() searches keys.

It's also easier to see what's going on when you use descriptive variable names.

We can also skip the del entirely and make this more Pythonic, using a dict comprehension:

def x_remove(input_dict, word):
    return {key: value for key, value in input_dict if key not in word}

This will still implicitly create a shallow copy of the list (without the removed elements) and return it. This will be more performant as well.

As stated in the comments, all keys in dictionaries are unique. There can only ever be one key named 'a' or b.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download