for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
Answer from dr jimbob on Stack Overflowfor i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
The globals() function returns a dictionary containing all your global variables.
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}
There is also a similar function called locals().
I realise this is probably not exactly what you want, but it may provide some insight into how Python provides access to your variables.
Edit: It sounds like your problem may be better solved by simply using a dictionary in the first place:
fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
Have you considered creating a class? A class can be viewed as a wrapper for a dictionary.
Copy# Generate some variables in the workspace
a = 9; b = ["hello", "world"]; c = (True, False)
# Define a new class and instantiate
class NewClass(object): pass
mydict = NewClass()
# Set attributes of the new class
mydict.a = a
mydict.b = b
mydict.c = c
# Print the dict form of the class
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
Or you could use the setattr function if you wanted to pass a list of variable names:
Copymydict = NewClass()
vars = ['a', 'b', 'c']
for v in vars:
setattr(mydict, v, eval(v))
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
You can write your own function for create_dict
Copydef create_dict(*args):
return dict({i:eval(i) for i in args})
a = "yo"
b = 7
print (create_dict("a", "b"))
Which gives {'a': 'yo', 'b': 7} output.
Here's a simple generator for the same:
Copyvars = ["a", "b"]
create_dict = {i:eval(i) for i in args}
or you can use this one-liner lambda function
Copycreate_dict = lambda *args: {i:eval(i) for i in args}
print (create_dict("a", "b"))
But if you want to pass the variables to the function instead of the variable name as string, then its pretty messy to actually get the name of the variable as a string. But if thats the case then you should probably try using locals(), vars(), globals() as used by Nf4r
Turn the dictionary keys into variable names with same values in Python from .mat Matlab files using scipy.io.loadmat - Stack Overflow
How to Convert dictionary into local variables inside the function?
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)? - Stack Overflow
python - Dictionary key name from variable - Stack Overflow
Not sure if the title is very clear, let me explain alil.
In javascript, you can create an object like so:
field1 = "aaa"
field2 = "bbb"
testObj = {
field1,
field2
}
>>> testObj
>>> { field1: "aaa", field2: "bbb" }Is there a way to do this in python, where the variable name become the key's name, and the variable value becomes the key-value pair's value? My current use case btw is I have a function that takes 4 arguments, which are used to create a dict, like so.
def foo(arg1, arg2, arg3, arg4):
dict1 = {
"arg1" : arg1,
"arg2" : arg2,
"arg3" : arg3,
"arg4" : arg4
}
...I would like to use *args and make this function flexible, but im not sure how to create the dictionary using this method. Thanks in advance
In python, method parameters can be passed as dictionnaries with the ** magic:
def my_func(key=None):
print key
#do the real stuff
temp = {'key':array([1,2])}
my_func(**temp)
>>> array([1,2])
The best thing to do is to use temp['key']. To answer the question, however, you could use the exec function. The benefits of doing it this way is that you can do this don't have to hard code any variable names or confine yourself to work inside a function.
from numpy import array,matrix
temp = {'key':array([1,2]),'b': 4.3,'c': 'foo','d':matrix([2,2])}
for k in temp:
exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = repr(temp[k])))
>>> key
array([1, 2])
>>> b
4.3
>>> c
'foo'
>>> d
matrix([[2, 2]])
NOTE : This will only work if you have imported the specific function from the modules. If you don't want to do this because of code practice or the sheer volume of function that you would need to import, you could write a function to concatenate the module name in front of the entry. Output is the same as the previous example.
import numpy as np,numpy
temp = {'key':np.array([1,2]),'b': 4.3,'c': 'foo','d':np.matrix([2,2])}
def exec_str(key,mydict):
s = str(type(mydict[key]))
if '.' in s:
start = s.index("'") + 1
end = s.index(".") + 1
v = s[start:end:] + repr(mydict[key])
else:
v = repr(mydict[key])
return v
for k in temp:
exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = exec_str(k,temp)))
While this isn't the best code practice, It works well for all of the examples I tested.
Forget filtering locals()! The dictionary you give to the formatting string is allowed to contain unused keys:
>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> locals()
{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}
>>> '%(name)s %(zip)i' % locals()
'foo 123'
With the new f-string feature in Python 3.6, using locals() is no longer necessary:
>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> f'{zip: >5} {name.upper()}'
' 123 FOO'
You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below:
dict((name, eval(name)) for name in list_of_variable_names)
In addition, if you know, for example, that the variables exist in the local symbol table you can save yourself from the dangerous eval by looking the variable directly from locals:
dict((name, locals()[name]) for name in list_of_variable_names)
After your final update, I think the answer below is really what you want. If you're just using this for string expansion with strings that you control, just pass locals() directly to the string expansion and it will cherry-pick out the desired values
If, however, these strings could ever come from an outside source (e.g. translation files), than it's a good idea to filter locals()
You want something like:
data_dict = {}
s = "jane"
data_dict[s] = {}
data_dict[s]['name'] = s
That should work, though I would recommend instead of a nested dictionary that you use a dictionary of names to either namedtuples or instances of a class.
Try this:
data_dict = {}
s = ["jane", "jim"]
for name in s:
data_dict[name] = {}
data_dict[name]['name'] = name
data_dict[name]['email'] = name + '@example.com'