喜欢 列表理解 ,Python允许字典理解。我们可以使用简单的表达式创建字典。 词典理解的形式是 {key:iterable中(key,value)的值}
null
让我们来看一个例子,假设我们现在有两个名为keys和value的列表,
# Python code to demonstrate dictionary # comprehension # Lists to represent keys and values keys = [ 'a' , 'b' , 'c' , 'd' , 'e' ] values = [ 1 , 2 , 3 , 4 , 5 ] # but this line shows dict comprehension here myDict = { k:v for (k,v) in zip (keys, values)} # We can use below too # myDict = dict(zip(keys, values)) print (myDict) |
输出:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
我们还可以使用理解从列表中制作词典
# Python code to demonstrate dictionary # creation using list comprehension myDict = {x: x * * 2 for x in [ 1 , 2 , 3 , 4 , 5 ]} print (myDict) |
输出:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
比如,
sDict = {x.upper(): x * 3 for x in 'coding ' } print (sDict) |
输出:
{'O': 'ooo', 'N': 'nnn', 'I': 'iii', 'C': 'ccc', 'D': 'ddd', 'G': 'ggg'}
我们可以将字典理解用于if和else语句以及其他表达式。下面的示例将数字映射到不可被4整除的立方体:
# Python code to demonstrate dictionary # comprehension using if. newdict = {x: x * * 3 for x in range ( 10 ) if x * * 3 % 4 = = 0 } print (newdict) |
输出:
{0: 0, 8: 512, 2: 8, 4: 64, 6: 216}
本文由 Shantanu Sharma。 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END