I am struggling with getting the output that I want. I have a list and a dictionary as illustrated below:
h3_rules = [[{'LA'}, {'KE'}, 0.9468308801441875], [{'KE'}, {'LA'}, 0.9650949173300674], [{'EH'}, {'LA', 'KE'}, 0.9136231884057971], [{'LA'}, {'EH', 'KE'}, 0.9468308801441875], [{'KE'}, {'LA', 'EH'}, 0.9650949173300674], [{'LA', 'EH'}, {'KE'}, 0.9471153846153846], [{'EH', 'KE'}, {'LA'}, 0.9650949173300674], [{'LA', 'KE'}, {'EH'}, 1.0], [{'EH'}, {'KE'}, 0.9466666666666667], [{'KE'}, {'EH'}, 1.0], [{'LA'}, {'EH'}, 0.99969960949234], [{'EH'}, {'LA'}, 0.9646376811594203]]
and
h3_S = {'EH': [0.33326893353941267], 'KE': [0.31549459041731065], 'LA': [0.321580370942813], 'PR': [0.029656105100463678]}
I want to append a value to the nested lists if the first index of the nested list matches the dictionary key. The value that I want to append is calculated by dividing the last index of the nested list with the value of the corresponding dictionary key. Below a handwritten example of what I hope to achieve using the first nested list as an example. The first index of the nested list is set "LA":
h3_rules = [[{'LA'}, {'KE'}, 0.9468308801441875, (0.9468308801441875/0.321580370942813], ...]
Currently I have the code below but I am stuck at checking if the list values matches the key and using the value for division.
# For every rule in rules
for i in h3_rules:
# Check if the first index for every rule matches a dictionary key
if h3_rules[i][0] == ?:
# If there is a match append the newly calculated value based on the key value to the list
h3_rules[i].append(h3_rules[i][-1] / ?)
print(h3_rules)
I have looked extensively in Stack overflow but I couldn't find anything. Any idea on how I can achieve the desirable result?
According to the way h3_rules
is defined, then first you need to validate if the first index is an instance of a set
, grab the first value of the set, and then just append the corresponding division.
for h in h3_rules:
first_element = next(iter(h[0])) if isinstance(h[0], set) else None
if first_element is not None: h.append(h[-1]/h3_S[first_element][0])