I\'m looking for a way to create dictionary without writing the key explicitly I want to create function that gets number variables, and create dictionary where the variables na
No, there isn't, because Python functions don't get information about the variables used to call the function. Also, imagine doing something like this:
create_dict_from_variables(first_name[:-3] + "moo", last_name[::2])
The function will have no way of knowing the expressions used to create the parameters.
You cannot do this.
Your function could be defined as:
def create_dict_from_variables(first_name, second_name):
return something_from(first_name, second_name)
and you can call this function:
create_dict_from_variables('abcd', 'efgh')
These two arguments 'abcd'
and 'efgh'
are not named variables.
In principle this is possible by passing variable names to function create_dict
and then reaching to a caller stack frame from within create_dict
function using module inspect
.
In fact, there is a way:
from varname import nameof
def foo(first_name,second_name):
return {nameof(first_name):first_name, nameof(second_name):second_name}
first_name = "daniel"
second_name = "daniel"
print (foo(first_name,second_name))
Output:
{'first_name': 'daniel', 'second_name': 'daniel'}
You can get the python-varname
package below:
https://github.com/pwwang/python-varname
Basic use:
from varname import nameof
s = 'Hey!'
print (nameof(s))
Output:
s
You can use locals, but I would recommend against it. Do it explicitly.
>>> import this
[...]
Explicit is better than implicit.
[...]
Your code will generally be better, more predictable, less prone to breaking and more comprehensible if you do it explicitly.
You can't do it without writing at least the variable names, but a shorthand can be written like this:
>>> foo = 1
>>> bar = 2
>>> d = dict(((k, eval(k)) for k in ('foo', 'bar')))
>>> d
{'foo': 1, 'bar': 2}
or as a function:
def createDict(*args):
return dict(((k, eval(k)) for k in args))
>>> createDict('foo','bar')
{'foo': 1, 'bar': 2}
you can also use globals()
instead of eval()
:
>>> dict(((k, globals()[k]) for k in ('foo', 'bar')))