Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?

1 Answer

0 votes
by (106k points)

The first thing you can do to filter the dict to contain only certain keys you can constructing a new dict:

dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }

This is another nicer way to filter the dict for that you will removing everything in-place you will only keep the values that you want to:

unwanted = set(keys) - set(your_dict) for unwanted_key in unwanted: del your_dict[unwanted_key]

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
+1 vote
1 answer

Browse Categories

...