Ad

Fastest Way To Add Many Parameters With Their Names As Keys To A Dict Programmatically

- 1 answer

During many projects, I find myself very frequently assigning variables to a dict, where the name of the variable is the key and the variable's value is the value in the dict. For instance:

def create_results_dict(age, sex, ...):
    res = {}
    res['age'] = age
    res['sex'] = sex
    ...
    return res

I'm wondering what would be a pythonic and efficient (in terms of execution speed) way to doing these assignments dynamically/programmatically? I.e., so that one does not have to write all the assignments manually (lines 3-5, in my example).

Edit: The parameters are just one or more positional or named parameters, i.e., a variable that has a name and a value. I guess, fundamentally the question is, can I receive programmatically the name of a parameter/variable (from a list of parameters passed to a function)?

Ad

Answer

Simple Method using locals:

def create_results(age, sex, marital_status = "single"):
    return {k:v for k, v in locals().items() if not k.startswith('__')}

res = create_results(34, "male")

print(res)

Output:

{'marital_status': 'single', 'sex': 'male', 'age': 34}
Ad
source: stackoverflow.com
Ad