如何在Python中优雅地创建字典?

原创 谁践踏了优雅 2025-02-06 23:48 45阅读 0赞

在 Python 中,优雅地创建字典可以通过使用字典推导式(dictionary comprehension)或者 dict() 函数来实现。

以下是两种方法的示例:

  1. 使用字典推导式:
    ```python

    创建一个列表

    numbers = [1, 2, 3]

使用字典推导式创建字典

dict_of_numbers = {n: n**2 for n in numbers}}

print(dict_of_numbers) # 输出:{1: 1, 2: 4, 3: 9}}

  1. 2. 使用 dict() 函数:
  2. ```python
  3. numbers = [1, 2, 3]
  4. # 使用 dict() 函数创建字典
  5. dict_of_numbers = dict(zip(numbers, [n**2 for n in numbers]])))
  6. print(dict_of_numbers) # 输出:{1: 1, 2: 4, 3: 9}}

这两种方法都可以优雅地在 Python 中创建字典。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,45人围观)

还没有评论,来说两句吧...

相关阅读