这个表达式称为dict理解(本质上是创建字典的单行表达式)。在
在Python中,dict如下所示:dictionary = {"key": "value", "anotherkey": ["some", "other", "value"]}
其中:的右边是键(通常是字符串),:的左边是分配给键的值。在
您可以使用字典从如下键中获取值:
^{pr2}$
因此,dict comprehension使用类似于您示例中的表达式来构建字典。在
如果您有这个basket:basket = ["apple", "apple", "banana"]
set(basket) # set() returns a set of unique items from basket.
>> {"apple", "banana"}
basket.count("apple") # list.count(x) returns the number of times x occurs in list.
>> 2
这个:dictionary = {}
for fruit in set(basket):
dictionary[fruit] = basket.count(fruit)
return dictionary
与此相同:return {fruit: basket.count(fruit) for fruit in set(basket)}
# {^key : ^value} is added for each item in set(basket)
他们都回来了:{"apple": 2, "banana": 1}