删除字典中的键/值对不起作用

时间:2018-11-21 18:52:01

标签: python dictionary key-value

我正试图通过定义这样的python函数从字典中删除一些键/值对:

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)

问题是new_dict_a等于dict_a而没有删除两对(0:value1)和(2:value3)。 我在做什么错了?

1 个答案:

答案 0 :(得分:2)

这会为您做

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)

输出:

{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}