Search code examples
pythonlist-comprehensiondictionary-comprehension

List/Dict comprehension in Python to update a dictionary with keys and values from a string


Does anyone know how to convert below for loop into a list or dictionary comprehension in one line? type(letter) = string,type(stringOne) = string,type(dictResult) = dictionary.For example, stringOne = 'abcddd', I want the output to be dictResult = {'a': 1, 'b': 1, 'c': 1, 'd': 3} Thanks!!!

stringOne = 'abcddd'
dictResult = {}
for letter in stringOne:
    dictResult[letter] = dictResult.get(letter,0) + 1

Solution

  • Find unique keys with set and then count. Note the set doesn't not keep (keys) insertion order!

    stringOne = 'abcddd'
    
    dictResult = {char: stringOne.count(char) for char in set(stringOne)}
    
    print(dictResult)