How to Get Subset of Dictionary in Python and simplify Your Effort

Here's a way to make a subset out of a Dictionary in Python. The key and values in a dictionary wrap in curling brackets. So by seeing the format, you can easily recognize the dictionary.

Below are ideas with sample logic and how it works. It is useful for your projects and interviews too.


Subset from a Dictionary in Python


Example dictionary

To illustrate, I have taken a dictionary as below with keys and values.

my_first_dict = {

'HP' : 100
'IBM': 200
'NTT' : 300
'ABC' : 400
'GDF' : 500
}

I want to make a subset of values greater than 100 and less than 400. How can you achieve this? No worries, below, you will find the logic.


Logic to get subset out of a dictionary

I am using dictionary comprehension to achieve this.

Syntax:


sub_set = { key:value for key, value in my_first_dict.items() value >100 and value <400}


Result

Dictionary comprehension


References

Post a Comment

Thanks for your message. We will get back you.

Previous Post Next Post