Python字典迭代 [英] Python dictionary iteration
本文介绍了Python字典迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
dict2
,我想要迭代,并删除所有包含特定ID号的条目 idlist
。 dict2 [x]
是列表列表(请参见下面的示例dict2)。这是迄今为止写的代码,但是它不会删除 idlist中的所有ID(条目[1]
)的所有实例
。任何帮助? dict2 = {G1:[[A,'123456',C,D],[A,'654321 ',C,D],[A,'456123',C,D],[A,'321654',C,D]]}
idlist = ['123456','456123' ,'321654']
for dict在dict2.keys()中:
for dict2 [x]中的条目:
如果idlist中的条目[1]:
dict2 [x] .remove(entry)
如果dict2 [x] == []:
del dict2 [x]
dict2
应该最终看起来像这样:
dict2 = {G1:[[A,'654321',C,D]]}
for dict.keys()中的$:
dict2 [k] = [x for dict2 [k] if x [1] not in idlist]
如果不是dict2 [k]:
del dict2 [k]
I have a dictionary dict2
which I want to iter through and remove all entries that contain certain ID numbers in idlist
. dict2[x]
is a list of lists (see example dict2 below). This is the code I have written so far, however it does not remove all instances of the IDs (entry[1]
) that are in the idlist
. Any help?
dict2 = {G1:[[A, '123456', C, D], [A, '654321', C, D], [A, '456123', C, D], [A, '321654', C, D]]}
idlist = ['123456','456123','321654']
for x in dict2.keys():
for entry in dict2[x]:
if entry[1] in idlist:
dict2[x].remove(entry)
if dict2[x] == []:
del dict2[x]
dict2
should end up looking like this :
dict2 = {G1:[[A, '654321', C, D]]}
解决方案
Try a cleaner version perhaps?
for k in dict2.keys():
dict2[k] = [x for x in dict2[k] if x[1] not in idlist]
if not dict2[k]:
del dict2[k]
这篇关于Python字典迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文