Open In App

Dictionary items in value range in Python

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop.

Using Loop

The idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items in a new dictionary.

Python
d = {'a': 10, 'b': 15, 'c': 20, 'd': 5}

# Initialize an empty dictionary to store filtered items
res = {}

# Iterate through each key-value pair in dictionary
for key, val in d.items():

    # Check if value is within range
    if 10 <= val <= 20:  

        # Add matching items to new dictionary
        res[key] = val  
print(res)

Output
{'a': 10, 'b': 15, 'c': 20}

Let’s explore other different methods to extract dictionary items within a specific value range:

Using Dictionary Comprehension

We can use dictionary comprehensions to filter and create new dictionaries in a single line of code. It is a preferred method for clean and readable code.

Python
d = {'a': 10, 'b': 15, 'c': 20, 'd': 5}

# Iterates through items and includes
# those where value lies between 10 and 20
res = {key: val for key, val in d.items() if 10 <= val <= 20}

print(res)

Output
{'a': 10, 'b': 15, 'c': 20}

Explanation:

  • d.items(): Extracts key-value pairs from dictionary
  • Dictionary comprehension: Iterates through items and includes those value lies between 10 and 20

Using filter() Function

An alternative to dictionary comprehension is use filter() function combined with a lambda function.

Python
d = {'a': 10, 'b': 15, 'c': 20, 'd': 5}

res = dict(filter(lambda item: 10 <= item[1] <= 20, d.items()))
print(res)

Output
{'a': 10, 'b': 15, 'c': 20}

Explanation:

  • filter(): Applies a condition to each item in the dictionary.
  • Lambda function: Specifies the range condition (10 <= item[1] <= 20).
  • dict(): Converts the filtered items back into a dictionary.

Next Article
Practice Tags :

Similar Reads

  翻译: