Reputation: 55
I have a nested diciotnary that contains lists. I want to remove a list item if it is the string 'maybe'. I tried with a one liner below but it isnt removing the 'maybe' value. Could someone point me in the right direction? Thank you!
# my dictionary
d = {'x':{'a':['yes', 'no', 'maybe'], 'b': ['yellow', 'maybe']}, 'y':{'a': ['sometimes', 'maybe'], 'c':['no']}}#, 'fop':{'a':0.145, 'b': numpy.nan, 'c':0.485}}
# my attempt
{ k: {a: b for a, b in v.items() if b != 'maybe'} for k, v in d.items()}
Upvotes: 0
Views: 358
Reputation: 4529
Problem is that you b is a list an not the elements of that list, so you have to find the string within that list.
{ k: {a: [bb for bb in b if bb != 'maybe' ] for a, b in v.items() } for k, v in d.items()}
if you want to do that with list comprehensions
Upvotes: 1