简体   繁体   中英

Removing key/value pair in a dictionary is not working

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?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM