I have 2 dictionary
- I need to check the values of keys of
d2
in d1
by passing code
, Name
, module
- if all matches then extract
details
from the d2
then split by |
and take the length of it
- Then check the length of above and
count(%s)
from d1
- if both are same then extract
MessageRole
and construct a Message
from d1
d1 = [ { "Name": "Country", "module": "Request", "code": 11101, "Message": "Data Approved %s", "MessageRole": "Country User" }, { "Name": "Country", "module": "Request", "code": 11102, "Message": "Data Granted %s", "MessageRole": "Country User" }, { "Name": "Country", "module": "Request", "code": 11103, "Message": "Data Denied %s %s", "MessageRole": "Country User" }, { "Name": "Country", "module": "Request", "code": 11201, "Message": "Data Request %s %s %s", "MessageRole": "Data Owner" } ]
d2 = { "Name" : "Country", "module": "Request", "code" : 11201, "details": "A|B|C" }
My code is below
Role = ''
Message = ''
for each in d1:
#I need to check the values of keys of `d2` in `d1` by passing `code`, `Name`, `module`
if each["code"] == d2['code'] and
each["Name"] == d2['Name'] and
each["module"] == d2['module']:
#if all matches then extract `details` from the `d2` then split by `|` and take the length of it
details = tuple(d2['details'].split('|'))
print(details)
variables = len(details)
print(variables)
# Then check the length of above and `count(%s)` from d1
if variables == each["Message"].count('%s'):
# if both are same then extract `MessageRole` and construct a `Message` from d1
Role = each["MessageRole"]
Message = each["Message"] % ("<i>%s</i>" % details)
Expected out is below
My Role
will be having
Data Owner
My Message
will be having
Data Request <i>A</i> <i>B</i> <i>C</i>
question from:
https://stackoverflow.com/questions/65847626/how-to-compare-two-dictionaries-and-substitute-a-string-from-the-value 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…