1

I am trying to delete some key/value pairs from a dictionary by defining a python function like this :

def removekey(d, key_list):
    r = d.copy()
    for h in key_list:
        r.pop(h, None)
        #del r[h]
    return r

keys_to_delete = (0,2)    
dict_a = {0: 277.8646380131756, 1: 237.68252216827375, 2: 223.04941947616766, 3: 9.058932480795093, 4: 175.74552982744078, 5: 4.834328204426816, 6: 180.5798580318676, 7: 45144.9645079669}

new_dict_a = removekey(dict_a,keys_to_delete)

Issue is that new_dict_a is equal to dict_a without removing the two pairs (0: value1) and (2: value3). What am I doing wrong?

Alex
  • 67
  • 1
  • 8
  • Possible duplicate of [Understanding dict.copy() - shallow or deep?](https://stackoverflow.com/questions/3975376/understanding-dict-copy-shallow-or-deep) – mustaccio Nov 21 '18 at 18:54

1 Answers1

1

This will do for you:

def removekey(d, key_list):
    r = d.copy()
    for key in key_list:
        r.pop(key)
    return r

keys_to_delete = (0,2)
dict_a = dict_a = {0: 277.8646380131756, 1: 237.68252216827375, 2: 223.04941947616766,
                   3: 9.058932480795093, 4: 175.74552982744078, 5: 4.834328204426816,
                   6: 180.5798580318676, 7: 45144.9645079669}

new_dict_a = removekey(dict_a,keys_to_delete)
print(new_dict_a)
print(dict_a)

Output:

{1: 237.68252216827375, 3: 9.058932480795093, 4: 175.74552982744078, 5: 4.834328204426816, 6: 180.5798580318676, 7: 45144.9645079669}
{0: 277.8646380131756, 1: 237.68252216827375, 2: 223.04941947616766, 3: 9.058932480795093, 4: 175.74552982744078, 5: 4.834328204426816, 6: 180.5798580318676, 7: 45144.9645079669}
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19
  • Well, but the items are float values not strings , I just put value1, value2 and so on to avoid reporting them. My dictionary is already defined like this : {0: 277.8646380131756, 1: 237.68252216827375, 2: 223.04941947616766, 3: 9.058932480795093, 4: 175.74552982744078, 5: 4.834328204426816, 6: 180.5798580318676, 7: 45144.9645079669} – Alex Nov 21 '18 at 19:04
  • It does not matter what your values are as you are using keys to remove the item, even if its float its should work. – Sanchit Kumar Nov 21 '18 at 19:09
  • The suggested code is same that I posted and It's not working. I get the same dictionary. – Alex Nov 21 '18 at 19:11
  • It's surely working for me and it should work for you as well. I edited the answer taking float values from the question. – Sanchit Kumar Nov 21 '18 at 19:15
  • You're right, It was my mistake in passing a wrong value as second parameter. Sorry again. Then, my code was already working. Can I delete this question? – Alex Nov 21 '18 at 19:20
  • It's completely up to you. I am happy to help :) – Sanchit Kumar Nov 21 '18 at 19:22
  • Ok, I am going to leave it here just in case someone has a similar question. – Alex Nov 21 '18 at 19:31