pythonpython-3.xdictionarykeyerror

KeyError in Python though the key exists in dictionary


I am solving a leetcode problem 17. Letter Combinations of a Phone Number. I have coded this solution using Python3.

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        transform={}

        transform[2]=["a","b","c"]
        transform[3]=["d","e","f"]
        transform[4]=["g","h","i"]
        transform[5]=["j","k","l"]
        transform[6]=["m","n","o"]
        transform[7]=["p","q","r","s"]
        transform[8]=["t","u","v"]
        transform[9]=["w","x","y","z"]

        def fun(digits,idx):
            if idx==len(digits):
                return []
            letters=transform[digits[idx]]
            ans=[]

            for letter in letters:
                temp=fun(digits,idx+1)
                for ele in temp:
                    ele=letter+ele
                ans+=temp

            return ans

        return fun(digits,0)

But I am stuck with this keyerror:

KeyError: '2'
    letters=transform[digits[idx]]
Line 17 in fun (Solution.py)
    return fun(digits,0)
Line 28 in letterCombinations (Solution.py)
    ret = Solution().letterCombinations(param_1)
Line 47 in _driver (Solution.py)
    _driver()
Line 58 in <module> (Solution.py)

I have also seen with this line print(f"transform.keys()={transform.keys()}"). I am getting transform.keys()=dict_keys([2, 3, 4, 5, 6, 7, 8, 9]) as stdout. Here the key 2 is present. But I can't understand why the KeyError: '2' is raised.

Please help me how to fix this error.


Solution

  • you haven't given us the full code, such as ways that you are calling the class.

    If I understand correctly, the reason is because you're setting the key to be an integer, such as 2 or 3, however the digits variable is of type string, and when you try to access transform[digits[idx]], you are treating digits[idx] as if it were an integer too. However, in Python, indexing a string returns a character, not an integer. That's why you are getting a KeyError.

    Try this code instead, please tell me if it does not work, and tell us the full code, as in how you're calling it:

    class Solution:
        def letterCombinations(self, digits: str) -> List[str]:
            transform = {}
    
            transform[2] = ["a", "b", "c"]
            transform[3] = ["d", "e", "f"]
            transform[4] = ["g", "h", "i"]
            transform[5] = ["j", "k", "l"]
            transform[6] = ["m", "n", "o"]
            transform[7] = ["p", "q", "r", "s"]
            transform[8] = ["t", "u", "v"]
            transform[9] = ["w", "x", "y", "z"]
    
            def fun(digits, idx):
                if idx == len(digits):
                    return []
                letters = transform[int(digits[idx])]
                ans = []
    
                for letter in letters:
                    temp = fun(digits, idx + 1)
                    for ele in temp:
                        ele = letter + ele
                    ans += temp
    
                return ans
    
            return fun(digits, 0)