I have an input dictionary like this
dict1= {'AM': ['tv', 'rs', 'pq', 'MN', 'tN', 'tq', 'OP', 'tP', 'QR', 'tr'],
'BR': ['tv', 'rs', 'pq', 'MN', 'tN', 'tq', 'OP', 'tP', 'QR', 'tr']}
Two other dictionaries in which I want to search are
dict2_1={'AM':{'pq':1.2,'rs':2.41,'tv':3.81},'BR':{'MN':1.3,'OP':1.41,'QR':1.81}}
dict3_1={'AM':{'tq':1.3,'rs':1.41,'tv':2.41},'BR':{'tN':1.8,'tP':1.81,'tr':1.42}}
Expected Output
{'AM-tv': (3.81,2.41),
'AM-rs': (2.41,1.41),
'AM-pq': (1.2,'insert'),
'AM-MN': ('insert','insert'),
'AM-tN': ('insert','insert'),
'AM-tq': ('insert',1.3),
'AM-OP': ('insert','insert'),
'AM-tP': ('insert','insert'),
'AM-QR': ('insert','insert'),
'AM-tr': ('insert','insert'),
'BR-tv': ('insert','insert'),
'BR-rs': ('insert','insert'),
'BR-pq': ('insert','insert'),
'BR-MN': (1.3,'insert'),
'BR-tN': ('insert',1.8),
'BR-tq': ('insert','insert'),
'BR-OP': (1.41,'insert'),
'BR-tP': ('insert',1.81),
'BR-QR': (1.81,'insert'),
'BR-tr': ('insert',1.42)}
In the output, there is a need to generate pairs of dict1. if the values of dict1 are present within the inner nested dictionary keys of dict2_1 or dict2_2 then it will replace with the inner nested dictionary values otherwise it will replace it with 'insert'. Is there any way to do it?
CodePudding user response:
You could use dict.get
to set a default value if a key doesn't exist in a dict (in this case "insert"):
out = {}
for k, lst in dict1.items():
for v in lst:
out[f"{k}-{v}"] = (dict2_1[k].get(v, 'insert'), dict3_1[k].get(v, 'insert'))
The above code can also be written as a dict comprehension:
out = {f"{k}-{v}": (dict2_1[k].get(v, 'insert'), dict3_1[k].get(v, 'insert')) for k, lst in dict1.items() for v in lst}
Output:
{'AM-tv': (3.81, 2.41),
'AM-rs': (2.41, 1.41),
'AM-pq': (1.2, 'insert'),
'AM-MN': ('insert', 'insert'),
'AM-tN': ('insert', 'insert'),
'AM-tq': ('insert', 1.3),
'AM-OP': ('insert', 'insert'),
'AM-tP': ('insert', 'insert'),
'AM-QR': ('insert', 'insert'),
'AM-tr': ('insert', 'insert'),
'BR-tv': ('insert', 'insert'),
'BR-rs': ('insert', 'insert'),
'BR-pq': ('insert', 'insert'),
'BR-MN': (1.3, 'insert'),
'BR-tN': ('insert', 1.8),
'BR-tq': ('insert', 'insert'),
'BR-OP': (1.41, 'insert'),
'BR-tP': ('insert', 1.81),
'BR-QR': (1.81, 'insert'),
'BR-tr': ('insert', 1.42)}