单行for循环构建字典?

2024-03-12

我正在构建一个字典(稍后我会将其转换为 JSON 字符串)。我这样构造它:

data = {}
for smallItem in bigList:
    data[smallItem] = smallItem

我怎样才能使 for 循环第一行?


您可以使用听写理解 https://docs.python.org/3/reference/expressions.html#dictionary-displays:

data = {smallItem:smallItem for smallItem in bigList}

您也可以使用dict https://docs.python.org/3/library/functions.html#func-dict and a 生成器表达式 https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression:

data = dict((smallItem, smallItem) for smallItem in bigList)

但听写理解会更快。

至于将其转换为 JSON 字符串,您可以使用json.dumps https://docs.python.org/3/library/json.html#json.dumps.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

单行for循环构建字典? 的相关文章

随机推荐