Frage

I am trying to create a dictionary of directory's which pass a certain condition. It's important that each directory is set as a value, and that each key is numbered starting from 1.

I have written something here which does just that, but I was wondering if there was a better way of doing this?

dict(enumerate(sorted([x for x in os.listdir("T:\\") if certain_condition(x)]), start=1))

result:

{1: 'folderA', 2: 'folderB', 3: 'folderC', 4: 'folderD', 5: 'folderE', 6: 'folderF'}

Many thanks

War es hilfreich?

Lösung

Just use a list instead:

[None] + sorted([x for x in os.listdir("T:\\") if certain_condition(x)]

You can access each value by index, starting at 1.

If your keys were not just sequential integers and / or you need to remove items from this without altering indices, a dict comprehension would work too:

{'A{}'.format(i + 1): v for i, v in enumerate(sorted(x for x in os.listdir("T:\\") if certain_condition(x)))}

or you could use a itertools.count() object to provide the counter for you:

from itertools import count
index = count(1)

{'A{}'.format(next(index)): v for v in sorted(os.listdir("T:\\") if certain_condition(v)}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top