How to Extract a Subset from a Dictionary in Python

Problem Formulation and Solution Overview

This article will show you how to extract a subset from a Dictionary in Python.

Our article works with a Dictionary called cars, containing 30 key:value pairs: a name and associated horsepower.

{'Chevrolet Chevelle Malibu': '130.0', 'Buick Skylark 320': '165.0', 'Plymouth Satellite': '150.0', 'AMC Rebel SST': '150.0', 'Ford Torino': '140.0', 'Ford Galaxie 500': '198.0', 'Chevrolet Impala': '220.0', 'Plymouth Fury iii': '215.0', 'Pontiac Catalina': '225.0', 'AMC Ambassador DPL': '190.0', 'Citroen DS-21 Pallas': '115.0', 'Chevrolet Chevelle Concours (sw)': '165.0', 'Ford Torino (sw)': '153.0', 'Plymouth Satellite (sw)': '175.0', 'AMC Rebel SST (sw)': '175.0', 'Dodge Challenger SE': '170.0', "Plymouth 'Cuda 340": '160.0', 'Ford Mustang Boss 302': '140.0', 'Chevrolet Monte Carlo': '150.0', 'Buick Estate Wagon (sw)': '225.0', 'Toyota Corolla Mark ii': '95.0', 'Plymouth Duster': '95.0', 'AMC Hornet': '97.0', 'Ford Maverick': '85.0', 'Datsun PL510': '88.0', 'Volkswagen 1131 Deluxe Sedan': '46.0', 'Peugeot 504': '87.0', 'Audi 100 LS': '90.0', 'Saab 99e': '95.0', 'BMW 2002': '113.0'}

πŸ’¬ Question: How would we write code to extract a subset from a Dictionary?

We can accomplish this task by one of the following options:

Also, feel free to check out our full guide on a similar topic, i.e., reducing the number of elements in a dictionary:

πŸ‘‰ Recommended Tutorial: How to Filter a Dictionary in Python? (… The Most Pythonic Way)


Method 1: Use dict.items() and list

This example uses dict.items() to extract the first five (5) key:value pairs from a Dictionary.

first_five = dict(list(cars.items())[:4])
print(first_five)

The above is a one-liner that extracts the first five (5) key:value pairs from the cars dictionary by doing the following:

  • The list() function is called and passed one (1) argument, cars.items().
  • Then, the first five (5) entries are extracted using slicing ([:4]).
  • Next, the list is converted back into a Dictionary.

The results are output to the terminal.

{'Chevrolet Chevelle Malibu': '130.0', 'Buick Skylark 320': '165.0', 'Plymouth Satellite': '150.0', 'AMC Rebel SST': '150.0'}

Method 2: Use Dictionary Comprehension and sorted()

This example uses Dictionary Comprehension and sorted() to return the first three (3) sorted key:value Dictionary pairs.

sorted_three = {k: cars[k] for k in sorted(cars.keys())[:3]}
print(sorted_three)

The above code sorts the cars Dictionary based on the key portion of the key:value pair and returns the first three (3) pairs that result from the sort.

The results are output to the terminal.

{'AMC Ambassador DPL': '190.0', 'AMC Hornet': '97.0', 'AMC Rebel SST': '150.0'}

Method 3: Use Dictionary Comprehension dict.items()

This example uses Dictionary Comprehension and dict.items() to extract values from a key:value pair where the value is greater than a specified amount.

hpower = {key: value for key, value in cars.items() if float(value) >= 220.0}
print(hpower)

The above code uses Dictionary Comprehension to iterate through the cars Dictionary. During the iteration, each value is converted from a string to a float and tested to see if it is greater than or equal to (>=) 220.0. If True, the key:value pair is appended to hpower.

The results are output to the terminal.

{'Chevrolet Impala': '220.0', 'Pontiac Catalina': '225.0', 'Buick Estate Wagon (sw)': '225.0'}

Method 4: Use Dictionary Comprehension and in

This example uses Dictionary Comprehension and in to extract key:value pairs where the value is in the specified list.

hpower = {key: value for key, value in cars.items() if float(value) in [115.0, 220.0]}
print(hpower)

The above code uses Dictionary Comprehension to iterate through the cars Dictionary. During the iteration, each value is converted from a string to a float and tested to see if the value exists in the specified list. If this is true, the key:value pair is appended to hpower.

The results are output to the terminal.

{'Chevrolet Impala': '220.0', 'Citroen DS-21 Pallas': '115.0'}

Method 5: Use Dictionary Comprehension and enumerate()

This example uses Dictionary Comprehension and enumerate(). This function allows you toΒ loop over an iterable and associated counter to extract specific key:value pairs based on a condition.

top_ten = {kv[0]:kv[1] for i, kv in enumerate(cars.items()) if i <= 10}
print(top_ten)

This code uses Dictionary Comprehension and enumerate() to iterate through the loop. If the counter (i) is less than or equal to (<=) 10, then key:value pair is appended to top_ten.

The results are output to the terminal

{'Chevrolet Chevelle Malibu': '130.0', 'Buick Skylark 320': '165.0', 'Plymouth Satellite': '150.0', 'AMC Rebel SST': '150.0', 'Ford Torino': '140.0', 'Ford Galaxie 500': '198.0', 'Chevrolet Impala': '220.0', 'Plymouth Fury iii': '215.0', 'Pontiac Catalina': '225.0', 'AMC Ambassador DPL': '190.0', 'Citroen DS-21 Pallas': '115.0'}

Summary

This article has provided 5 ways to extract a subset from a dictionary to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programming Humor