CodexBloom - Programming Q&A Platform

How can I efficiently filter a large dictionary based on a nested condition in Python 3.10?

👀 Views: 489 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-24
python dictionary filtering performance Python

I'm reviewing some code and I'm performance testing and I'm sure I'm missing something obvious here, but I have a large dictionary where each key maps to another dictionary... My goal is to filter this dictionary based on a specific condition applied to the nested dictionaries. For example, suppose I have the following structure: ```python my_dict = { 'item1': {'price': 100, 'stock': 20}, 'item2': {'price': 150, 'stock': 0}, 'item3': {'price': 200, 'stock': 5}, } ``` I want to create a new dictionary that includes only the items that are in stock (i.e., where the `stock` value is greater than 0) and also have a price less than 200. I tried using dictionary comprehension, but I ended up with an empty dictionary: ```python filtered_dict = { k: v for k, v in my_dict.items() if v['stock'] > 0 and v['price'] < 200 } print(filtered_dict) # Output: {} ``` I expected `filtered_dict` to contain `item1` and `item3`, but it seems like I'm missing something. I also want to know if there's a performance consideration when dealing with larger dictionaries, as `my_dict` can grow quite large (thousands of items). Is there a better way to perform this filtering, or am I overlooking something in the comprehension? Also, should I be concerned about the performance of this operation, and if so, how can I optimize it? Thanks in advance! This issue appeared after updating to Python 3.11. Could someone point me to the right documentation?