Search code examples
pythondictionary-comprehension

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


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.


Solution

  • 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}