Home > Backend Development > Python Tutorial > How can I efficiently filter dictionaries based on custom conditions in Python?

How can I efficiently filter dictionaries based on custom conditions in Python?

DDD
Release: 2024-11-11 12:20:02
Original
779 people have browsed it

How can I efficiently filter dictionaries based on custom conditions in Python?

Advanced Dictionary Filtering with Custom Conditions

The book's example illustrates dictionary filtering using the items() function, a process that can be streamlined for efficiency.

Dict Comprehension Method:

Python offers a powerful tool for this purpose: the dict comprehension. With it, you can create a new dictionary based on existing values while applying custom conditions. For instance, to filter a dictionary of points:

points = {'a': (3, 4), 'b': (1, 2), 'c': (5, 5), 'd': (3, 3)}

points_under_5 = {
    k: v
    for k, v in points.items()  # Iterate over (key, value) pairs
    if v[0] < 5 and v[1] < 5  # Filter based on condition
}
Copy after login

Python 2 Compatibility:

In Python 2 (2.7 onwards), the syntax for iterating over dictionary items is slightly different:

points_under_5 = {
    k: v
    for k, v in points.iteritems()  # Use 'iteritems()' instead of 'items()'
    if v[0] < 5 and v[1] < 5
}
Copy after login

Performance Considerations:

The dict comprehension approach offers superior performance compared to the manual iteration method:

import timeit

# Manual iteration
manual_time = timeit.timeit(
    """
points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)}
points_small={}
for item in [i for i in points.items() if i[1][0]<5 and i[1][1]<5]:
    points_small[item[0]]=item[1]
""", number=1000000
)

# Dict comprehension
dict_time = timeit.timeit(
    """
points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)}
points_under_5 = {k:v for k, v in points.items() if v[0]<5 and v[1]<5}
""", number=1000000
)

print("Manual iteration time:", manual_time)
print("Dict comprehension time:", dict_time)
Copy after login

The above is the detailed content of How can I efficiently filter dictionaries based on custom conditions in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template