为什么这个嵌套的字典理解在 Python 中不起作用?

Why isn't this nested dict comprehension working in Python?

nested_dict = { b: { a: some_other_source_dict[b][a] or {} for a in a_list } for b in b_list }

如果some_other_source_dict[b][a]存在,正确的输出应该是:

nested_dict = { b_key_1: { a_key_1: a_val_1, a_key_2: a_val_2 },
                b_key_2: { a_key_1: a_val_3, a_key_2: a_val_4 } }

如果不存在,输出应该是:

nested_dict = { b_key_1: { a_key_1: {}, a_key_2: {} },
                b_key_2: { a_key_1: {}, a_key_2: {} } }

some_other_source_dict[b][a] 如果不存在,return 不是假值,它只是错误。你想要像 { a: some_other_source_dict[b][a] for a in a_list } if "some_other_source_dict" in globals() else {} 这样的东西。最好,你应该有一些方法来确定它是否被定义而不需要检查 globals().