[英]Python removing specific values from a dictionary
I have the following python dictionary of integers: 我有以下整数的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]}
I would like to remove the number 6 from both the 5th and 6th entries to the dictionary. 我想从字典的第5和第6个条目中删除数字6。 I know this is quite simple but I am new to python so all help appreciated.
我知道这很简单,但是我是python的新手,因此感谢所有帮助。 Thank you.
谢谢。
as straight-forward as you'd think: 如您所想般直截了当:
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)
as list
s are mutable sequence types they have a .remove(element)
method. 因为
list
是可变序列类型,所以它们具有.remove(element)
方法。
You can define a function for this. 您可以为此定义一个函数。 Given a dictionary
d
: 给定字典
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]}
Use list.remove
on each entry: 在每个条目上使用
list.remove
:
my_dict[5].remove(6)
my_dict[6].remove(6)
You can also remove values with list comprehensions: 您还可以使用列表推导删除值:
>>> 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]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.