Heim > Artikel > Backend-Entwicklung > Wie können Sie ein Wörterbuch basierend auf einer benutzerdefinierten Bedingung effizient bereinigen?
Pruning a Dictionary Based on a Custom Condition
When working with dictionaries, it is often useful to refine their contents based on specified criteria. Suppose you have a dictionary of points represented as tuples, and you're interested in extracting only points where both the x and y coordinates are less than 5.
Traditionally, one approach involves iterating over the dictionary items using a list comprehension:
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]
While this method is functional, there is a more succinct solution using a dictionary comprehension:
points_small = {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
This concise expression generates a new dictionary where keys and values satisfy the specified condition. Similarly, in Python 2.7 and above, the following syntax can be used:
points_small = {k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
By employing dictionary comprehensions, you gain an elegant and efficient means to filter dictionaries based on arbitrary conditions, providing a more streamlined approach to data manipulation.
Das obige ist der detaillierte Inhalt vonWie können Sie ein Wörterbuch basierend auf einer benutzerdefinierten Bedingung effizient bereinigen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!