[Python] Filtering defaultdict with dictionary comprehension

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    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 my code:

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


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

    This 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? What's a good way of doing either?

    Continue reading...

Compartilhe esta Página