Skip to main content
 首页 » 编程设计

python之python中的联合字典

2025年04月02日20findumars

我想连接多个字典以返回我的函数。

def get_params(request, active_id): 
 
    tab_parameters = [ 
        shadow(active_id), 
        light_parameter(active_id) 
    ] 
 
    parameters = { 
        'id': active_id, 
        'parameters': tab_parameters 
    } 
 
    return response.HttpResponse(json.dumps(parameters), 'application/json') 
 
 
def light_parameter(active_id): 
    active_lights = LightParameter.objects.filter(id=active_id).all() 
 
    list_parameters = [] 
    for active_light in active_lights: 
        list_parameters.append({ 
                'name': 'light', 
                'color': active_light.color, 
        }) 
 
    return list_parameters 

预期结果是:

{ 
    "id": 1, 
    "parameters": [ 
        { 
            "name": "shadow" 
        }, 
        { 
            "color": 1,  
            "name": "light" 
        }, 
        { 
            "color": 2,  
            "name": "light" 
        } 
} 

我的实际结果是(带[]):

{ 
    "id": 1, 
    "parameters": [ 
        { 
            "name": "shadow" 
        }, 
        [ 
            { 
                "color": 1,  
                "name": "light" 
            }, 
            { 
                "color": 2,  
                "name": "light" 
            } 
        ] 
} 

有什么想法吗?我已经尝试使用联合、更新、连接但没有成功..

谢谢!

请您参考如下方法:

这实际上并不涉及 dict。您只需正确合并组成 tab_parameters 的列表即可。

tab_parameters = [shadow(active_id)] + light_parameter(active_id)