【问题标题】:Single line for-loop to build a dictionary?单行for循环构建字典?
【发布时间】:2015-02-27 05:20:37
【问题描述】:

我正在构建一个字典(稍后我将把它变成一个 JSON 字符串)。我是这样构造的:

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

如何让 for 循环一行?

【问题讨论】:

    标签: python for-loop dictionary


    【解决方案1】:

    实际上在这种特定情况下,您甚至不需要字典理解,因为您使用的是重复的键/值对

    >>> bigList = [1, 2, 3, 4, 5]
    >>> dict(zip(bigList, bigList))
    {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
    

    【讨论】:

    • 这实际上让我学习了一种新方法zip+1
    【解决方案2】:

    您可以使用dict comprehension

    data = {smallItem:smallItem for smallItem in bigList}
    

    您也可以使用dictgenerator expression

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

    但是dict理解会更快。

    至于转换成JSON字符串,可以使用json.dumps

    【讨论】:

    • dict 带有生成器表达式的唯一优点是它适用于 Python2.6 及以下版本,这可能很重要
    • 谢谢,我是python的新手,一直在找这个功能的名字。
    • 好答案。谢谢。只是想知道 - 如果我想将此应用于多个字段,语法应该是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多