简体   繁体   English

Python中字典理解中的键、值分配

[英]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} . 这个答案指出正确的语法是{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 ?这是否意味着我不能使用下面的代码并创建一个更优雅的 oneliner 来从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 .我正在尝试从路径创建字典键,然后从 static 子文件夹/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.我尝试了a = {v: k for k, v in enumerate(os.listdir(path))}变体,但根据我的评论,我不清楚它是否可以通过 Dictionary Comprehension 实现。

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:对于os.listdir(path)返回的每个元素(在我的例子中是命名item ),创建以下key: value对,其中:

  1. key - item关键物品
  2. value - the expression os.listdir(path + "/" + item + "/urls") value - 表达式os.listdir(path + "/" + item + "/urls")

This should work when you have defined path :当您定义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.唯一的问题是在计算的路径不存在时检查FileNotFoundError异常。 So if you risk producing invalid paths, I'd recommend you go with the original syntax.因此,如果您冒着产生无效路径的风险,我建议您使用原始语法 go。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM