Counting elements with dictionary
Let’s say you want to find how many times each element is present in the list or tuple.
Normal approach words = ['a', 'the', 'an', 'a', 'an', 'the'] d = {} for word in words: if word in d: d[word] += 1 else: d[word] = 1 print d {'a': 2, 'the': 2, 'an': 2} Better approach words = ['a', 'the', 'an', 'a', 'an', 'the'] d = {} for word in words: d[word] = d.
[Read More]