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:
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]