Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – non-clumsy way to enumerate over filtered dictionary

I have a code like this (d is some dictionary and s is some set):

for i, (k, v) in enumerate((k, v) for k, v in d.items() if k in s):
    ...

Even if we ignore the ugly repetition, all literals actually have substantial length, so repeating k and v 3 times is not an option. What’s the best way to write it? Right now, we use the following (also ugly) option:

i = -1
for k, v in d.items():
    if k not in s:
        continue
    i += 1
    ...

Another option:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for i, (k, v) in enumerate((k, d[k]) for k in d if k in s):
    ...

, but it basically has the same amount of repetitions.

I’m OK with using any library which is shipped by default (i.e. without pip install).

>Solution :

With one extra line, but much less complexity, you could do:

for i, k in enumerate(filter(s.__contains__, d)):
    v = d[k]

A variation of this uses set intersection (that may scramble your insertion order though):

for i, k in enumerate(s & d.keys()):
    v = d[k]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading