2017-05-03 95 views
-2

我正在用Python写作使用键创建词典

我有一个名为“位置”的元组列表。这些元组中的某些元素在'职位'中有超过1个。我想用代码创建一个名为d的字典:

d["positions"] = dict.fromkeys(positions) 

这给了我一个预期的字典,每个键的每个值都等于无。但是现在我希望这些值等于元组在“职位”中出现的次数。这是可能的,而不必迭代列表'位置'或不使用诸如positions.count(x)之类的东西?

亚历

+1

这听起来像你想有一个'collections.Counter()' –

+0

请你张贴的字典。 –

回答

0
import collections 


lt = [ (1,2) , (2,3) , (2,3) , (4,5) , (1,2)] 

counter = collections.Counter() 
counter.update(lt) 
print(dict(counter)) 

结果

{(1, 2): 2, (2, 3): 2, (4, 5): 1}