0

I am having a hard time wrapping my head around Dictionary Comprehension.

This answer states the correct syntax is {key: value for (key, value) in iterable}.

Does that mean I cannot take the below code and create a more elegant oneliner to create a dictionary from an os.listdir?

import os

d = {}
for item in os.listdir(path):
    d[item] = os.listdir(path + "/" + item + "/urls")

I am trying to create a dictionary key from the path, then create values from the static subfolder /urls.

{'foo': ['bar','bah'], 'foo1': ['bar1', 'bah1']}

I've tried variations of a = {v: k for k, v in enumerate(os.listdir(path))} but am unclear based off my review if it's even possible via Dictionary Comprehension.

Gabio
  • 9,126
  • 3
  • 12
  • 32
ImNotLeet
  • 381
  • 5
  • 19

2 Answers2

2

Try:

d = {item: os.listdir(path + "/" + item + "/urls") for item in os.listdir(path)}

Explanation:

For each element returned by os.listdir(path) (named item in my case), the following key: value pair is created where:

  1. key - item
  2. value - the expression os.listdir(path + "/" + item + "/urls")
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • Any chance you can edit the answer to Explain like I'm 5? I'd like to know where conceptually I don't understand the syntax of the solution. – ImNotLeet Apr 16 '21 at 15:44
0

This should work when you have defined path:

d = {item: os.listdir(path + "/" + item + "/urls") for item in os.listdir(path)}

Only problem is to check for FileNotFoundError exceptions when the computed path doesn't exist. So if you risk producing invalid paths, I'd recommend you go with the original syntax.