Add dict key from list if list value isn't already a dict key

Viewed 48

Is there a way to make the following code more efficient? Namely, how can I avoid the need to first make the empty dict?


lst = [1,1,2,2,3,4,4,4]

dct = {}

dct = {num: lst.count(num) for num in lst if num not in dct}

Thank you.

2 Answers

You may use a set():

lst = [1,1,2,2,3,4,4,4]

dct = {key: lst.count(key) for key in set(lst)}
print(dct)

Which yields

{1: 2, 2: 2, 3: 1, 4: 3}

@Sushanth's solution is the best optimized:

import collections

lst = [1,1,2,2,3,4,4,4]

dct = collections.Counter(lst)
print(dct)
Related