Categories
Python Answers

How to filter a dict to contain only certain keys with Python?

Spread the love

Sometimes, we want to filter a dict to contain only certain keys with Python.

In this article, we’ll look at how to filter a dict to contain only certain keys with Python.

How to filter a dict to contain only certain keys with Python?

To filter a dict to contain only certain keys with Python, we can use dictionary comprehension.

For instance, we write:

d = {'foo': 1, 'foobar': 2, 'bar': 3}

foodict = {k: v for k, v in d.items() if k.startswith('foo')}
print(foodict)

We have a dict d with a few keys.

And we want to create a dict that has the entries with keys that starts with 'foo'.

To do this, we loop through the items with for k, v in d.items().

And then we call k.startswith('foo') to return only the entries that starts with 'foo'.

Therefore, foodict is {'foo': 1, 'foobar': 2}.

Conclusion

To filter a dict to contain only certain keys with Python, we can use dictionary comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *