阅读python dict或yaml,并使用参数和对象作为python函数调用

阅读python dict或yaml,并使用参数和对象作为python函数调用,python,object,dictionary,yaml,Python,Object,Dictionary,Yaml,阅读下面的python dict或其等效yaml并生成等效python函数调用 其yaml(为了可读性): 我想阅读上述类型的yaml或python dict,并调用如下: RouteAdd(route_config=Routeconfig(app_id="my app",nexthops=[NexthopInfo(if_name="my interface",nexthop_address=GatewayAddress(ethernet_mac="my mac",nexthop_ip="my

阅读下面的python dict或其等效yaml并生成等效python函数调用

其yaml(为了可读性):

我想阅读上述类型的yaml或python dict,并调用如下:

RouteAdd(route_config=Routeconfig(app_id="my app",nexthops=[NexthopInfo(if_name="my interface",nexthop_address=GatewayAddress(ethernet_mac="my mac",nexthop_ip="my ip"),nexthop_index=2)],table_name="my table"))

基本上,备用层次结构是一个对象。我贴的是一个小夹子。正在寻找一个递归函数,通过读取yaml或python dict并将其转换为上述格式,以便调用和执行该函数来实现这一点。非常感谢您的帮助。谢谢

尝试了论坛中建议的所有方法,但不知何故,没有一种方法能解决我所寻找的问题。因此,作为一个初学者,通过以下非正统的查找和替换方法解决了这个问题。如果有人有更好的解决方案,请张贴,我想使用它

api_map_complete = {api: {'config': {'AddressConfig': {'unit': 0, 'port_name': "my_name", 'address': "my address", 'family': 2}}}} 

def dict_to_obj(mystr,flag):
    global api_string
    if re.search(':\(',mystr):    
        if flag % 2 == 0:    
            api_string=mystr.replace(":(","(",1)
            flag=flag+1
        else:
            api_string=mystr.replace(":("," = (",1)
            flag=flag+1
        dict_to_obj(api_string,flag)
    else:    
        mystr=mystr.replace(":"," = ")
        mystr=mystr.replace(",",", ")
        api_string=mystr    

for combo in api_map_complete:    

    api_name=combo.keys()[0]
    for k,v in combo.iteritems():
        api_string=str(v)
        api_string=api_string.replace("{","(")
        api_string=api_string.replace("}",")")
        api_string=api_string.replace(" ","")
        api_string=api_string.replace(":'",":\"")
        api_string=api_string.replace("',","\",")
        api_string=api_string.replace("')","\")")
        api_string=api_string.replace("'","")
        dict_to_obj(api_string,1)
    #print api_string
    api_obj=api_name+api_string
    print api_obj
试试这个:

def call_dict(d):
    k, v = list(d.items())[0]  # ('RouteAdd', {route_config: ...})
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = call_dict(v2)
        elif isinstance(v2, list):
            kwargs[k2] = [(call_dict(v3) if isinstance(v3, dict) else v3) for v3 in v2]
        else:
            kwargs[k2] = v2
    return globals()[k](**kwargs)
测试:

Upd:

作为代码字符串:

def str_of_code(d):
    k, v = list(d.items())[0]
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = str_of_code(v2)
        elif isinstance(v2, list):
            kwargs[k2] = '[{}]'.format(', '.join(
                (str_of_code(v3) if isinstance(v3, dict) else repr(v3)) for v3 in v2)
            )
        else:
            kwargs[k2] = repr(v2)
    return '{}({})'.format(k, ', '.join('{}={}'.format(*i) for i in kwargs.items()))


test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = str_of_code(test_dict)
print(res)  # test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])

这无法处理以下列表:dicts@germn谢谢你调查。这很好,但我想将输出提取为字符串,以将其集成到我的其他工作中。因此,是否可以提取字符串形式的调用格式:“test1(t_arg=1,t_arg2=[test2(t_arg=2),test2(t_arg=3)]”。再次感谢。@German,它因测试而中断。{'test1':{'t_arg':1,'t_arg2':{'t_arg3':[{'a':1},{'b:2'}}}。你能在这里帮忙吗?@Suren你希望这个有什么输出?@German,如果test_dict={'func_name':{'input':{'AsList':{'a_list':[{'AEntry':{'entry':{'entry':2,'exit':3}}}}}}}},预期的输出是func_name(input=AsList(a_list=[AEntry(entry=2,exit=3)])@Suren,而
stru的代码
对我来说适用于这个dict。(如果你得到了错误,请用这个命令写下错误消息和行)但是它对
{'some':[{'a':1},{'b:2'}]}
不起作用,因为不清楚
{'a':1}
部分
'some
的参数或函数
a
是否有错误的参数。
def call_dict(d):
    k, v = list(d.items())[0]  # ('RouteAdd', {route_config: ...})
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = call_dict(v2)
        elif isinstance(v2, list):
            kwargs[k2] = [(call_dict(v3) if isinstance(v3, dict) else v3) for v3 in v2]
        else:
            kwargs[k2] = v2
    return globals()[k](**kwargs)
def test1(t_arg=None, t_arg2=None):
    return t_arg + sum(t_arg2)

def test2(t_arg=None):
    return t_arg


res = test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])
print(res)  # 6


test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = call_dict(test_dict)
print(res)  # 6
def str_of_code(d):
    k, v = list(d.items())[0]
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = str_of_code(v2)
        elif isinstance(v2, list):
            kwargs[k2] = '[{}]'.format(', '.join(
                (str_of_code(v3) if isinstance(v3, dict) else repr(v3)) for v3 in v2)
            )
        else:
            kwargs[k2] = repr(v2)
    return '{}({})'.format(k, ', '.join('{}={}'.format(*i) for i in kwargs.items()))


test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = str_of_code(test_dict)
print(res)  # test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])