Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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
0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...