How to concatenate str and convert to a dict

Viewed 52
import numpy as np

a_var = np.array([1,2,3,5,67,9])
b_var = np.array([1,3,3,7,67,9])
b_var = np.array([1,5,3,7,77,10])
mydict = []

for i in dir():
    if i.endswith(_var):
        mydict += i

I got so many variables, I want the result of

mydict = {'a_var':a_var,'b_var':b_var,'b_var':b_var}. 

Is there any way to achieve it?

Many thanks

2 Answers

You can get all the variables defined in the current context with the python built-in function locals(). It is a dict.

see https://docs.python.org/3/library/functions.html#locals

You can get all the variables that end with '_var' by dict comprehension from the locals() dict:

{k:v for k,v in locals().items() if k.endswith('_var')}

You can use locals():

import numpy as np
a_var = np.array([1,2,3,5,67,9])
b_var = np.array([1,3,3,7,67,9])
b_var = np.array([1,5,3,7,77,10])

mydict = {}
for i in dir():
    if i.endswith('_var'):
        mydict.update({i:locals()[i]})
print(mydict)

Or, a dict comprehension:

mydict = {i:locals()[i] for i in dir() if i.endswith('_var')}


I do recommend this instead, which will give the same result:

import numpy as np

mydict = {}

mydict['a_var'] = np.array([1,2,3,5,67,9])
mydict['b_var'] = np.array([1,3,3,7,67,9])
mydict['b_var'] = np.array([1,5,3,7,77,10])

print(mydict)
Related