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")

# 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")


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:

Leave a Comment