简体   繁体   中英

Fast way variables into dict

I have a bunch of variables var1, var2, var3, ..., var99.

I like to have a dict where the name is the key and the key refers to the value of the variable. Currently I have to type

{
'var1': var1,
'var2': var2,
'var3': var3
...
}

Is there a faster way? Also I prefere pythonic answers of cause;)

Edit: An example I like to use

noise_std = np.mean(np.std(noise, axis=2))
noise_max = np.mean(np.max(noise, axis=2))
noise_min = np.mean(np.min(noise, axis=2))
noise_unique = len(torch.unique((torch.from_numpy(noise))))
noise_diff = (torch.sum(torch.abs(noise)) / (test_input.shape[1] * test_input.shape[2]) / 250).item()


result = {
    'id_file': id_file,
    'noise_unique': float(noise_unique),
    'noise_min': float(noise_min),
    'noise_max': float(noise_max),
    'noise_std': float(noise_std),
    'noise_diff': float(noise_diff)
    'snr_std': float(snr_std),
    'snr_mean': float(snr_mean),
    'macro_auc': float(macro_auc),
    'model_name': model_name,
    'n_iter': n_iter,
    'epsilon': epsilon
}

(Note: Some variables are from the parameters, later I need some of the variables. I just like to clear the code)

Edit 2: I like to a command like into_dict(macro_auc, n_iter, epsilon, snr_std)

You could use globals() and locals() to get a dict of global or local variables.

Example:

#!/usr/bin/env python3
import pprint

var1 = 1
var2 = "hello"

def my_func(arg):
    local_var = "there"
    print("globals:")
    pprint.pprint(globals())

    print("locals:")
    pprint.pprint(locals())

def main():
    my_func(99)


if __name__ == '__main__':
    main()

Output:

{'...': 'redacted',
 'main': <function main at 0x10b767430>,
 'my_func': <function my_func at 0x10b5ac0d0>,
 'pprint': <module 'pprint' from '/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/pprint.py'>,
 'var1': 1,
 'var2': 'hello'}
locals:
{'arg': 99, 'local_var': 'there'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM