Search code examples
pythonlistdictionarydictionary-comprehension

Assigning Key, Value in a Dictionary Comprehension in Python


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.


Solution

  • 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")