Press "Enter" to skip to content

Python Program to Extract a Subset of a Dictionary

Here is a Python program to extract a subset of a dictionary.

Extract a Subset of a Dictionary and Create a New Dictionary Using Python

The following Python program will extract, create and then will print the new dictionary for prices over 40. Also, will create and print another dictionary for fruits starting with letter P.

from pprint import pprint

prices = {
   'APPLE': 135.23,
   'MANGO': 62.78,
   'ORANGE': 202.43,
   'PEER': 44.20,
   'PEACH': 50.75
}

# Make a dictionary of all prices over 40
p1 = { key:value for key, value in prices.items() if value > 40 }

print("All prices over 40")
pprint(p1)

# Make a dictionary of fuites starting with P
tech_names = { 'PEER', 'PEACH' }
p2 = { key:value for key,value in prices.items() if key in tech_names }

print("All starting with P")
pprint(p2)

Output:

All prices over 40
{'APPLE': 135.23,
'MANGO': 62.78,
'ORANGE': 202.43,
'PEACH': 50.75,
'PEER': 44.2}
All starting with P
{'PEACH': 50.75, 'PEER': 44.2}

See also:

Vinish Kapoor

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Be First to Comment

    Leave a Reply

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