• Post author:
  • Post category:Python
  • Reading time:1 mins read

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

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.