-2
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: {} } }
Ice101781
  • 105
  • 10
  • 2
    [mcve], please. – user2357112 Mar 09 '18 at 22:08
  • 1
    [status-norepro](https://tio.run/##bY1NCsMgFIT37xRv2YKb/DQtQk8iIppYIrQa1CxK8OwmhhC66GaYGYZvpm8cnW1yDu6jhYuj9iK42fdaDKaP@MSloktNG9LSWyJd8ffNP1ICKd4mlAmrCbYc1Jkrgh0HsDpEPZwgVHQTSfH/F1OcSY4v51GisXjg096o0hwHCWDyxsbLD/@a8wo) – hyper-neutrino Mar 09 '18 at 22:10
  • @HyperNeutrino, thanks for your response. I'm not sure why, but it's still not working for me. I'm using Python 2.7 if that makes any difference. – Ice101781 Mar 09 '18 at 22:14
  • 1
    [no difference](https://tio.run/##bY1BCsMgFET3/xR/2YKb2DQtQk8iIppYIrQa1C5K8OwmhhC66GaYGYY30zeN3tFSon8b6dNogoz@E3ojB9snfODcsJmyC2nZNZOu@tvq7zmDki8b64RTgq0AfeSGYCcAnInJDAcINVtFMfz/xbXgSuDTB1RoHe74vDW6NvtBBpiCden0wz@XsgA) – hyper-neutrino Mar 09 '18 at 22:16
  • 1
    tell us what your exact code (`some_other_source_dict`, `a_list`, `b_list`, etc) and error is – hyper-neutrino Mar 09 '18 at 22:16
  • @HyperNeutrino, I got confused on what the problem itself actually was - apologies. Please see the updated version above. – Ice101781 Mar 09 '18 at 22:24
  • @HyperNeutrino, `a_list` and `b_list` are lists of strings, and `some_other_source_dict` is another nested dict, dense and complex, sourced from an XML response. – Ice101781 Mar 09 '18 at 22:28
  • It seems the problem may have something to do with the use of the inline `or` operator. – Ice101781 Mar 09 '18 at 22:31

1 Answers1

1

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().

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
  • Thanks for your patience with a Python noob. The strange thing is that if I specify the key-value pairs associated with `a_list` individually, and use `some_other_source_dict[b]['some_string_in_a'] or {}`, it works. I still don't understand why that would be the case, based on what you just explained. – Ice101781 Mar 09 '18 at 22:44
  • 1
    @Ice101781 are you sure the keys of each `some_other_source_dict[b]` are the same for all `b`? – hyper-neutrino Mar 10 '18 at 02:21
  • I'm embarrassed to admit it was a mismatched key issue. It now works as expected. Lesson learned: the simplest explanation is often the correct one. Thanks again for your insights and time. – Ice101781 Mar 10 '18 at 21:56