Reputation: 9253
I would like to eliminate entries in dictionary a and key-values for MyList if the second value is 8. I am missing something though.
My code:
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']
Desired Ouput:
[[1,2,3],[4,5,6]]
Upvotes: 0
Views: 54
Reputation: 13814
If you want to apply this in whole dictionary, you can do this:
for k in a:
a[k] = [ l for l in a[k] if l[1]!=8]
print a['Mylist']
Upvotes: 0
Reputation: 11
a = {
'Mylist' : [[1,2,3],[4,5,6],[7,8,9]]
}
a['Mylist'] = filter(lambda x: x[1] != 8, a['Mylist'])
print(a)
Result: {'Mylist': [[1, 2, 3], [4, 5, 6]]}
Upvotes: 0
Reputation: 1124758
You are looping over the keys of a
, not the sublists of a['Mylist']
.
The following corrects just the one value:
[sublist for sublist in a['Mylist'] if sublist[1] != 8]
To do so for all keys in the dictionary, nest this in a dictionary comprehension:
{key: [sublist for sublist in value if sublist[1] != 8]
for key, value in a.iteritems()}
Demo:
>>> 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]]}
Upvotes: 4