首页 > 解决方案 > 如果字典的键存储在变量中,如何获取字典中的值?

问题描述

我需要获取存储在变量中的键的值。变量的值会发生变化,并且输出模式应该会因此而变化。请检查下面的代码我似乎没有得到输出。只有当我可以传递给定键的值时,我才能得到它们。如果您指出此程序中的任何其他错误,那就太好了,因为我对此很陌生。谢谢 :)

self = {
       "1" : None,
       "0" : "",
       "2" : "abc",
       "3" : "def",
       "4" : "ghi",
       "5" : "jkl",
       "6" : "mno",
       "7" : "pqrs",
       "8" : "uvw",
       "9" : "wxyz"
}
def rec(rest_of_no, path):
        if not rest_of_no:
            combinations.add(path)
            return
        first, rest = rest_of_no[0], rest_of_no[1:]
        letters = self.get[int(first)] 

        for letter in letters:
            rec(rest_of_no, path)
            return combinations 

t = int(input())
for i in range(t):
    n = int(input())
    ar = list(map(int, input().split()))
    combinations = set()
    rec(ar, "")

    print (combinations)

这是我得到的错误:

    Runtime Error:
Runtime ErrorTraceback (most recent call last):
  File "/home/66ec1f75836d265709dd36b77f69f071.py", line 30, in <module>
    rec(ar, "")
  File "/home/66ec1f75836d265709dd36b77f69f071.py", line 19, in rec
    letters=self[int(first)] 
KeyError: 2

标签: pythonpython-3.xfunctionloopsdictionary

解决方案


你的代码有几件事。首先,为什么要使用eval

letters = self.get(first)  
# will do just fine instead of
letters = self.get(eval('first')) 

其次,self字典的键(对于不是传递给方法的实例的随机变量来说,这是一个非常糟糕的名称)是字符串。但ar包含整数,这就是为什么first是 anintself.get(first)返回的原因None

此外,正如 AndrejKesely 所指出的:

if not rec:
# should probably be 
if not rest_of_no:

并且具有相同参数的递归调用将导致无限递归,同时return rec返回一个函数对象,这可能不是您的意图。仍然需要大量调试;)


推荐阅读