Python Dictionary: How to Make Subset Easily

Here's an easy method to make a subset of a  Dictionary in Python. You already know that Dictionary has a format of Key, Value and enclosed in curling bracket.

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


Here is a Dictionary


my_first_dict = {

'HP' : 100

'IBM': 200

'NTT' : 300

'ABC' : 400

'GDF' : 500

}


I want to make a subset. The values are greater than 100 and less than 400. How can you achieve this? Don't worry you can do this easily. I am sharing logic with you.


Here is subset Logic: You Can do it Using Dictionary Comprehension

Syntax:

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

Result


References

Comments

Popular posts from this blog

How to Fix Python Syntax Errors Quickly

7 AWS Interview Questions asked in Infosys, TCS

Hyperledger Fabric: 20 Real Interview Questions