如何在Python中优雅地创建字典?
在 Python 中,优雅地创建字典可以通过使用字典推导式(dictionary comprehension)或者 dict() 函数来实现。
以下是两种方法的示例:
使用字典推导式创建字典
dict_of_numbers = {n: n**2 for n in numbers}}
print(dict_of_numbers) # 输出:{1: 1, 2: 4, 3: 9}}
2. 使用 dict() 函数:
```python
numbers = [1, 2, 3]
# 使用 dict() 函数创建字典
dict_of_numbers = dict(zip(numbers, [n**2 for n in numbers]])))
print(dict_of_numbers) # 输出:{1: 1, 2: 4, 3: 9}}
这两种方法都可以优雅地在 Python 中创建字典。
还没有评论,来说两句吧...