Python 将字典名称作为参数传递给查找函数

Python 将字典名称作为参数传递给查找函数,python,dictionary,Python,Dictionary,阿里特,这里是蟒蛇n00b,请温柔一点 从下面的代码中可以看到,我有一个函数,用于存储字典,其中包含有关我要解析并写入文件的不同列表的信息。我一直在研究如何将字典的名称传递给查找函数。如果我将其作为字符串传递,我会得到: AttributeError: 'str' object has no attribute 'get' 那么,问题是:如何传递lookup()要查找的字典的名称,例如参数“URL”,并返回结果 提前谢谢 #!/usr/bin/env python3 fr

阿里特,这里是蟒蛇n00b,请温柔一点

从下面的代码中可以看到,我有一个函数,用于存储字典,其中包含有关我要解析并写入文件的不同列表的信息。我一直在研究如何将字典的名称传递给查找函数。如果我将其作为字符串传递,我会得到:

AttributeError: 'str' object has no attribute 'get'
那么,问题是:如何传递lookup()要查找的字典的名称,例如参数“URL”,并返回结果

提前谢谢

  #!/usr/bin/env python3
    
    from re import sub
    from requests import get
    from ipaddress import ip_network
    
    def lookup(listname, key):
        
        spamhaus_drop = {
            "name"            :  "Spamhaus DROP",
            "URL"             :  "https://www.spamhaus.org/drop/drop.txt",
            "filename"        :  "spamhaus_drop.txt",
        }
    
        spamhaus_edrop = {
            "name"            :  "Spamhaus EDROP",
            "URL"             :  "https://www.spamhaus.org/drop/edrop.txt",
            "filename"        :  "spamhaus_edrop.txt",
        }
    
        return listname.get(key)
        
    def getnewlist(listname):
    
        req = get(lookup(listname, 'URL'))           
        newlist = spamhaus_parse(req.text)
        
        return newlist



    def main():
            newlist = getnewlist('spamhaus_drop')
            return(0)
        
   if __name__ == main():
       main()

你不能像那样动态地访问变量

将所有词典放在另一个词典中,并使用
listname
作为键

def lookup(listname, key):
    dicts = {
        'spamhaus_drop': {
            "name"            :  "Spamhaus DROP",
            "URL"             :  "https://www.spamhaus.org/drop/drop.txt",
            "filename"        :  "spamhaus_drop.txt",
            },
        
        'spamhaus_edrop': {
            "name"            :  "Spamhaus EDROP",
            "URL"             :  "https://www.spamhaus.org/drop/edrop.txt",
            "filename"        :  "spamhaus_edrop.txt",
            }
        }
    
    return dicts[listname].get(key)
您应该使用eval()像这样动态地访问变量

def lookup(listname, key):

    spamhaus_drop = {
        "name"            :  "Spamhaus DROP",
        "URL"             :  "https://www.spamhaus.org/drop/drop.txt",
        "filename"        :  "spamhaus_drop.txt",
    }

    spamhaus_edrop = {
        "name"            :  "Spamhaus EDROP",
        "URL"             :  "https://www.spamhaus.org/drop/edrop.txt",
        "filename"        :  "spamhaus_edrop.txt",
    }

    return eval(listname).get(key)

你的spamhaus_drop dict干什么?Eet verks!谢谢你!你来统治。我认为eval()不是一个好办法,因为这是一个安全风险?@DieterichBuxtehude如果用户动态提供输入而不进行过滤,这只是一个安全风险。但它仍然应该被视为最后的解决方案,几乎总是有更好的解决方案。