Home > Blockchain >  Python - non-clumsy way to enumerate over filtered dictionary
Python - non-clumsy way to enumerate over filtered dictionary

Time:11-18

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).

CodePudding user response:

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]

CodePudding user response:

dict comprehension is the fastest way to filter a dict:

filtered_dict = {key: value for key, value in d.items() if key in s}

Therefore, I would suggest to define a task function that does the job on the items and do everything inside this dict comprehension:

def task(key, value):
    # do the required job on the dict items
    ....
    return result


{key: task(key, value) for key, value in d.items() if key in s}

The result is a dict that contains the computed result for each key/value item. Of, course, you can add enumerateif an index is required in addition.

  • Related