根据某个值消除字典中的条目

时间:2014-12-22 15:58:13

标签: python python-2.7

如果第二个值为8,我想消除字典a中的条目和MyList的键值。虽然我遗漏了一些东西。

我的代码:

a = {
   'Mylist' : [[1,2,3],[4,5,6],[7,8,9]]
    }
a = [x for x in a if a['Mylist'][1] != 8]
print a['MyList']

所需的输出:

[[1,2,3],[4,5,6]]

3 个答案:

答案 0 :(得分:4)

您正在循环a,而不是a['Mylist']的子列表。

以下仅更正了一个值:

[sublist for sublist in a['Mylist'] if sublist[1] != 8]

要对字典中的所有键执行此操作,请将其嵌套在字典理解中:

{key: [sublist for sublist in value if sublist[1] != 8]
 for key, value in a.iteritems()}

演示:

>>> a = {
...    'Mylist' : [[1,2,3],[4,5,6],[7,8,9]]
...     }
>>> [sublist for sublist in a['Mylist'] if sublist[1] != 8]
[[1, 2, 3], [4, 5, 6]]
>>> {key: [sublist for sublist in value if sublist[1] != 8]
...  for key, value in a.iteritems()}
{'Mylist': [[1, 2, 3], [4, 5, 6]]}

答案 1 :(得分:0)

如果要在整个字典中应用此功能,可以执行以下操作:

for k in a:
    a[k] = [ l for l in a[k] if l[1]!=8]

print a['Mylist']

答案 2 :(得分:0)

a = {
   'Mylist' : [[1,2,3],[4,5,6],[7,8,9]]
    }
a['Mylist'] = filter(lambda x: x[1] != 8, a['Mylist'])
print(a)

结果: {' Mylist':[[1,2,3],[4,5,6]]}