
上QQ阅读APP看书,第一时间看更新
练习10:字典推导式
在最后一个有关字典的练习中,我们将学习比列表推导式还不常用的推导式——字典推导式;我们还将学习另外两种创建字典的方法,这在后续的学习中非常有用。
字典推导式与列表推导式的运行机制完全相同,但是需要同时指定键和值。
1.生成字典dict_1,其中键为0到9,值为键的平方:

输出如下:

能否在不用列表的情况下,使用字典推导式生成一个字典,其中键为0到9,值为键的平方根?
2.使用dict函数生成字典:

输出如下:

使用dict函数生成字典的另一种方式:

输出如下:

字典推导式功能众多。因此,上面两个dict命令都可以生成有效的字典。
注意上面有一对奇怪的值('Harry',300)。它是Python中另一种重要的基本数据类型——元组。我们将在下节中学习元组。