Filter a dictionary inside a tuple inside a list in Python

Is it possible to filter a dictionary, which is inside a tuple, which is inside a list based on it's keys in some list?

I have a list, each element in the list is a tuple, and the first element of each tuple is a dictionary. I want to only keep dictionary items whose keys are in some list.

How would I do this?

mifw_basemodel = ['word1', 'word2', 'word3', ...,'wordn']

train_set = [({'Blah': 1, 'blah2': 18, ...}, 'pos'),
             ({'worrrda':22, 'hmmmsa':12,  ...}, 'neg'),
             ({'duhduh':21, 'blahduh':12,  ...}, 'pos'),
               ...
             ({'foo':2, 'bar':4,  ...}, 'pos')]

This is what I am trying at the moment: { your_key: train_set[0][0][your_key] for your_key in train_set[0][0] if train_set[0][0].keys() in mifw_basemodel}

Upvotes: 1

Views: 88

Answers (1)

MasenCodes
MasenCodes

Reputation: 69

you iterate the initial list by its contents, and then for each content of the list, iterate through the dictionary using this syntax:

for key, value in content.items()
    if key in mifw_basemodel:
        new_list.append(value)

this examines the dictionary as a whole instead of trying to find each items keys

Upvotes: 1

Related Questions