-1

I have a defaultdict where keys are a number and values are lists with two entries each. I want to filter by a condition based on the first entry. I tried using the suggestion here: filter items in a python dictionary where keys contain a specific string

Here is the code I used:

circuits = {k:v for k,v in circuits.iteritems() if (v[0]+weightlimit <= histotal) in k}

After this code ran, I got an error about a missing key in the only spot in my code where I use the dictionary.

This of course means something is wrong, because a defaultdict does not do that. So it seems that the dictionary comprehension will change the defaultdict to a dictionary.

What is the best course of action here? Is it more efficient to use a different method of filtering, or is it more efficient to somehow cast my dictionary to defaultdict? And what's a good way of doing either?

Thank you!

Travis Black
  • 655
  • 4
  • 14

1 Answers1

2

A dict comprehension produces just that—a dict. Because you filtered, it's a dict now—not a defaultdict. You'll need to wrap it in a defaultdict if you want that behavior.

Unless there's a strong need for performance in this block, just stick to that approach. It's cleanest. But don't prematurely optimize. Profile your code and speed up the slow parts.

Arya McCarthy
  • 7,436
  • 3
  • 27
  • 48