Search code examples
pythondictionary-comprehension

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 }

If some_other_source_dict[b][a] exists, the correct output should be:

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 } }

If it doesn't exist, the output should be:

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

Solution

  • some_other_source_dict[b][a] doesn't return a falsy value if it doesn't exist, it just errors. You want something like { a: some_other_source_dict[b][a] for a in a_list } if "some_other_source_dict" in globals() else {}. Preferably, you should have some way of determining whether or not it's defined without needing to check globals().