How to merge Python dictionaries with the same keys, where a particular value will always be overwritten if the data is available

advertisements

How would i combine the two dictionaries below to form the new dictionary. The two dictionaries will either have a number or a Not Found field and i want the Not Found field to always be overwritten by a number. The dictionaries will always have the same keys and only 2 elements in each. This is an example.

Dict1: {'MaterialBC': '2261651270620793', 'RFIDBC': 'Not Found'}
Dict2: {'MaterialBC': 'Not Found', 'RFIDBC': '1022010911012012'}

NewDict: {'MaterialBC': '2261651270620793', 'RFIDBC': '1022010911012012'}

Is there an easier way to do this other than using if statements for each scenario?


This simplest I can think of is this,

 a = {'MaterialBC': '2261651270620793', 'RFIDBC': 'Not Found'}
 b = {'MaterialBC': 'Not Found', 'RFIDBC': '1022010911012012'}

 c = { k: a[k] if b[k] == 'Not Found' else b[k] for k in a.keys() }

It contains an if but it is a one-liner.

NB, this will prefer values from b if both a and b contain a number!