How to get dictionary keys without calculating the values

Viewed 33

I have existing code that defines a dictionary:

def func()
    ...
    map = {
      "aaa": expensive_operation1(),
      "bbb": expensive_operation2()
    }

I want to generate a list of the keys list = ["aaa", "bbb"] without having to execute the expensive value operations.

Of course, I could change the code like this:

KEY1 = "aaa"
KEY2 = "bbb"

LIST = [KEY1, KEY2]

def func()
    ...
    map = {
      KEY1: expensive_operation1(),
      KEY2: expensive_operation2()
    }

but then, if someone updates the dict with KEY3, they would have to remember to update both the dict and the LIST.

I'm open to any solution like lazy evaluations of the values, etc., just something maintainable and not error-prone.

1 Answers

To keep expensive_operation() from executing, you need to enclose it in a function:

def func()
    ...
    map = {
      "aaa": lambda:expensive_operation1(),
      "bbb": lambda:expensive_operation2()
    }

This will prevent the actual call to expensive_operation() until map["aaa"] is called map["aaa"](). You're free to do anything with the keys.

Related