I have a list of dictionaries. Each dictionary has certain boolean flags. So, the list looks like –
listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0},
{key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0},
...
{key1: somevalue(N-1), key2:somevalueN, flag1:True, flag2:False, score:0}]
Let’s say I have a table, that assigns scores based on the combination of values of the flags. It’s like a binary truth table:
flag1 True True False False
flag2 True False True False
score 1 2 3 4
I now want to iterate through the list, and assign these scores to each dictionary in the list, based upon the combination they specify. Is there an elegant way to do it, instead of if else loops? I have a lot of flags, and the combinations would increase with every new flag that’s added – result – the code is just ugly.
You can use a dictionary for this:
Now you can find the score by simply looking up
scores[flag1, flag2].To do this on the whole list, use