如何在Python中实现字典推导?
在Python中,字典推导(Dictionary Comprehension)是一种简洁的创建新字典的方法。基本语法如下:
{key: value for key, value in iterable}
其中:
key
是从原始数据源获取的值。value
是对key
进行某种操作的结果。iterable
可以是列表、元组、字典,甚至是其他可迭代对象。
以下是一些示例:
# 创建一个简单的字典推导
numbers = [1, 2, 3]
squared_numbers = {num: num ** 2 for num in numbers}}
print(squared_numbers) # 输出:{1: 1, 2: 4, 3: 9}}
# 使用字典作为输入进行推导
words = {'apple': 1, 'banana': 2}
count_by_word = {word: value for word, value in words.items() if word not in count_by_word}}
print(count_by_word)) # 输出:{'banana': 2, 'apple': 1}
以上就是如何在Python中实现字典推导的方法。
还没有评论,来说两句吧...