user10936564
user10936564

Reputation:

How can I remove a value in this list if it is not inside one of the keys of this nested dictionary?

Currently, I have the following weird nested dictionary:

d = {'start': {'0': {'start', 'near'}, '1': {'start'}}, 'near': {'1': {'end'}}, 'end': {}}

And the following list:

l = ['1', '0', '1', 'x', '0', '1']

If one of the values in l are not in one of the keys and values in the dictionary, remove it from the list.

So for example, in the list, there is an "x" and I am trying to see if there is anyway I can remove it with either l.remove() or if del / pop is better.

The thing that is giving me troubles is the dictionary.


What I have going so far:

d = {'start': {'0': {'start', 'near'}, '1': {'start'}}, 'near': {'1': {'end'}}, 'end': {}}
l = ['1', '0', '1', 'x', '0', '1']

for key, value in d.items():
    for keys, values in value.items():
        for number in l:

Upvotes: 1

Views: 55

Answers (1)

DYZ
DYZ

Reputation: 57105

Get the set of keys:

keys = set.union(*[set(x.keys()) for x in d.values()])
#{'0', '1'}

Filter out the non-keys:

result = [item for item in l if item in keys]
#['1', '0', '1', '0', '1']

Upvotes: 1

Related Questions