2

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?

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
ramailo sathi
  • 357
  • 1
  • 4
  • 22

2 Answers2

2

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}
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
1

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}
Taku
  • 31,927
  • 11
  • 74
  • 85
  • Any reasons for using deepcopy instead of just doing something like `d2= d.copy()` and `return d2` ? – ramailo sathi May 21 '17 at 01:09
  • d.copy() performs a shallow copy while deepcopy(d) performs a deep copy http://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm – Taku May 21 '17 at 01:10