dictionary-comprehensionopen-policy-agentrego

Rego object comprehension seems incomprehensible to me; lowercase the keys


In rego, I want to convert this:

d := {"a": "aye", "B": "bEe"}

to:

l := {"a": "aye", "b": "bEe"}

where the keys are all lowercased, but the values are not. How can this be done in one assignment line, or more if needed. I'd expect one of the following to work, but they don't, nor do any of the myriad of permutations I have tried similarly.

d := {"a": "aye", "B": "bEe"}
l1 := { k: lower(v) | k = d[_]; v = d[k] }
l2 := { k: lower(v) | k = d[_], v = d[k] }
l3 := { k : lower(v) |
  k = d[_]
  v = d[k]
}

In python this could be:

l = {k.lower(): v for k, v in d.items()}

How can the same be accomplished in rego?


More attempts (unworking) follow:

l4 := {k: v | k := lower(k), v := v}
l5 := {k: v | k := lower k, v := d[k]}
l6 := {k: v | k := lower(d[k]), v := d[k]}

Solution

  • In Rego, you can accomplish this with an object comprehension as follows where the comprehension will build a key: value "dictionary" implemented by iterating the object and setting the value and then setting the key to be lower case value of the key for each iteration:

    policy.rego:

    package example
    
    d := {"a": "aye", "B": "bEe"}
    l := { lowered_key: val | val := d[key]; lowered_key := lower(key) }
    

    Running this command:

    opa eval -d policy.rego "data.example":

    {
      "result": [
        {
          "expressions": [
            {
              "value": {
                "d": {
                  "B": "bEe",
                  "a": "aye"
                },
                "l": {
                  "a": "aye",
                  "b": "bEe"
                }
              },
              "text": "data.example",
              "location": {
                "row": 1,
                "col": 1
              }
            }
          ]
        }
      ]
    }
    

    References: