ramailo sathi
ramailo sathi

Reputation: 355

Deleting a dictionary item

I am trying to delete an item without using del, and I have the following code for it.

d = {'Red': 1, 'Green': 2, 'Blue': 3} 

def removeKey(dicts, keys):
    for k,v in dicts.iteritems():
        if k!= keys:
            dicts.update({k:v})
        else:
            continue
    return dicts


print removeKey(d, 'Red')

This prints everything including 'Red'. What am I doing wrong?

Upvotes: 2

Views: 606

Answers (2)

Taku
Taku

Reputation: 33764

You can deep copy the dict using the copy module to not modify the original dict, and pop the key from the copied dict:

from copy import deepcopy
d = {'Red': 1, 'Green': 2, 'Blue': 3}

def removeKey(d, key):
    d = deepcopy(d)
    d.pop(key, None)
    return d

print removeKey(d, 'Red')
# prints {'Green': 2, 'Blue': 3}

Upvotes: 1

Rushy Panchal
Rushy Panchal

Reputation: 17552

Your code never actually removes a key – instead, it just updates the original dictionary in-place if the key is not the key to remove; however, it doesn't do anything with the key to remove.

One option is to create a new dictionary:

def removeKey(dicts, keys):
    new_dict = {}
    for k,v in dicts.iteritems():
        if k != keys:
            new_dict[k] = v
    return new_dict

You also don't need the else: continue as that's implicit.

You can also condense this using a dictionary comprehension:

def removeKey(dicts, keys):
    return {k: v for k, v in dicts.iteritems() if k != keys}

Upvotes: 2

Related Questions