我有以下python的整数字典:
{1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
2: [3, 6, 13],
3: [1, 2, 3],
4: [13, 14, 15],
5: [3, 6],
6: [6, 13]}
我想将第5和第6个条目中的数字6删除到字典中。我知道这很简单,但我是python的新手所以所有人都很感激。谢谢。
答案 0 :(得分:3)
像你想象的那样直截了当:
dct = {1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
2: [3, 6, 13],
3: [1, 2, 3],
4: [13, 14, 15],
5: [3, 6],
6: [6, 13]}
dct[5].remove(6)
dct[6].remove(6)
print(dct)
由于list
为mutable sequence types,因此他们使用.remove(element)
方法。
答案 1 :(得分:3)
您可以为此定义一个功能。给定字典d
:
def remover(d, keys, value):
for k in keys:
d[k].remove(value)
return d
remover(d, [5, 6], 6)
# {1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
# 2: [3, 6, 13],
# 3: [1, 2, 3],
# 4: [13, 14, 15],
# 5: [3],
# 6: [13]}
答案 2 :(得分:2)
在每个条目上使用list.remove
:
my_dict[5].remove(6)
my_dict[6].remove(6)
答案 3 :(得分:1)
您还可以使用列表推导删除值:
>>> d = {1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],2: [3, 6,
13],3: [1, 2, 3],4: [13, 14, 15],5: [3, 6],6: [6, 13]}
>>> d[5] = [x for x in d[5] if x != 6]
>>> d[6] = [x for x in d[6] if x != 6]
>>> d
{1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2: [3, 6, 13], 3: [1, 2, 3], 4: [13, 14, 15], 5: [3], 6: [13]}