Python 字典生成式(dictionary comprehension)是一种简洁、高效的方式来创建字典。它基于列表生成式(list comprehension)的概念,允许你通过一个简短的语法来构建字典,而不需要编写显式的循环。
字典生成式的语法如下:
{ key_expression: value_expression for item in iterable }
这里是一个简单的例子,它创建了一个字典,其中的键是0到9的数字,值是每个数字的平方:
squared_dict = {x: x**2 for x in range(10)}
print(squared_dict)
# 输出:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 71}
你还可以在字典生成式中包含条件语句,来过滤出你想要的键值对:
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
# 输出:{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
下面是一些更高级的用法:
- 使用两个迭代器来生成字典:(映射方式生成字典)
pairs_dict = {x: y for x, y in zip(['a', 'b', 'c'], [1, 2, 3])}
print(pairs_dict)
# 输出:{'a': 1, 'b': 2, 'c': 3}
- 在生成字典时,对值进行更复杂的操作:
word_length = {word: len(word) for word in ['apple', 'banana', 'cherry']}
print(word_length)
# 输出:{'apple': 5, 'banana': 6, 'cherry': 6}
- 使用字典生成式来转换字典中的键和值:
original_dict = {'a': 1, 'b': 2, 'c': 3}
inverted_dict = {v: k for k, v in original_dict.items()}
print(inverted_dict)
# 输出:{1: 'a', 2: 'b', 3: 'c'}
字典生成式在处理数据转换和初始化时非常有用,可以使代码更加简洁和易于理解。
实操
import random
d = {item :random.randint(1, 100) for item in range(4)}
print(d)
lst = [1001, 1002, 1003]
lst2 = ['村民们', '我有用', '啦啦啦']
d = {key:value for key,value in zip(lst, lst2)}
print(d)
1109

被折叠的 条评论
为什么被折叠?



