How to filter a dict to contain only keys in a given list? [duplicate]

Both very new to Python and stackoverflow. Thank you for your patience, and your help.

I would like to filter a dict according to the content of a list like this:

d={'d1':1, 'd2':2, 'd3':3}

f = ['d1', 'd3']

r = {items of d where the key is in f}

Is this absurd?
If not, what would be the right syntax?

Thank you for your help.

Vincent

  • can you assume that the elements are all there?

    – 




  • What is the desired result if f is ['d1', 'd3', 'd99']?

    – 

  • Superset: stackoverflow.com/questions/2844516/python-filter-a-dictionary

    – 

Assuming you want to create a new dictionary (for whatever reason):

d = {'d1':1, 'd2':2, 'd3':3}
keys = ['d1', 'd3']

filtered_d = dict((k, d[k]) for k in keys if k in d)
# or: filtered_d = dict((k, d[k]) for k in keys)
# if every key in the list exists in the dictionary

You can iterate over the list with a list comprehension and look up the keys in the dictionary, e.g.

aa = [d[k] for k in f]

Here’s an example of it working.

>>> d = {'k1': 1, 'k2': 2, 'k3' :3}
>>> f = ['k1', 'k2']
>>> aa = [d[k] for k in f]
>>> aa
[1, 2]

If you want to reconstruct a dictionary from the result, you can capture the keys as well in a list of tuples and convert to a dict, e.g.

aa = dict ([(k, d[k]) for k in f])

More recent versions of Python (specifically 2.7, 3) have a feature called a dict comprehension, which will do it all in one hit. Discussed in more depth here.

Leave a Comment