如何从两个字典创建嵌套字典?

时间:2021-02-09 12:15:47

标签: python python-3.x dictionary

假设您有两本词典:

window.addEventListener('error', function (event) {
    const { error } = event;
    // Skip the first error, it is always irrelevant in the DEV mode.
    if (error.stack?.indexOf('invokeGuardedCallbackDev') >= 0 && !error.alreadySeen) {
        error.alreadySeen = true;
        event.preventDefault();
        return;
    }
    // Normal error handling.
}, { capture: true });

我怎样才能得到像这样的字典:

a = {'x': 1}
b = {'y': 2}

2 个答案:

答案 0 :(得分:2)

只需用冒号替换等号:

d = {
   'a' : {'x': 1},
   'b' : {'y': 2}
}

如果您有一个单独的词典列表,您可以在遍历列表时将其转换为具有词典理解的词典词典:

list_of_dicts =[{'x': 1}, {'y': 2}, {'z': 3}]
dict_of_dicts  ={idx:dic for idx, dic in enumerate(list_of_dicts)}

#{0: {'x': 1}, 1: {'y': 2}, 2: {'z': 3}}

答案 1 :(得分:1)

像这样:

new_dict = {
    'a': a,
    'b': b,
}