Ido*_*dok 16 python dictionary
我正在寻找一种方法来创建字典而无需显式写入键我想创建获取数字变量的函数,并创建字典,其中变量名称是键,它们的值是变量值
而不是编写以下功能:
def foo():
first_name = "daniel"
second_name = "daniel"
id = 1
return {'first_name':first_name, 'second_name':second_name}
Run Code Online (Sandbox Code Playgroud)
我希望得到与功能相同的结果:
create_dict_from_variables(first_name, second_name)
Run Code Online (Sandbox Code Playgroud)
无论如何都要这样做?
ade*_*min 26
pip install sorcery
from sorcery import dict_of
a = 1
b = 2
c = 3
d = dict_of(a, b, c)
print(d)
# {'a': 1, 'b': 2, 'c': 3}
Run Code Online (Sandbox Code Playgroud)
Not*_*fer 15
如果不写至少变量名称就不能这样做,但是可以这样写一个简写:
>>> foo = 1
>>> bar = 2
>>> d = dict(((k, eval(k)) for k in ('foo', 'bar')))
>>> d
{'foo': 1, 'bar': 2}
Run Code Online (Sandbox Code Playgroud)
或作为一种功能:
def createDict(*args):
return dict(((k, eval(k)) for k in args))
>>> createDict('foo','bar')
{'foo': 1, 'bar': 2}
Run Code Online (Sandbox Code Playgroud)
你也可以用globals()而不是eval():
>>> dict(((k, globals()[k]) for k in ('foo', 'bar')))
Run Code Online (Sandbox Code Playgroud)
您可以使用locals,但我建议您不要使用它。明确地做。
>>> import this
[...]
Explicit is better than implicit.
[...]
Run Code Online (Sandbox Code Playgroud)
如果你明确地这样做,你的代码通常会更好、更可预测、更不容易被破坏并且更容易理解。
eum*_*iro -4
你不可以做这个。
您的函数可以定义为:
def create_dict_from_variables(first_name, second_name):
return something_from(first_name, second_name)
Run Code Online (Sandbox Code Playgroud)
你可以调用这个函数:
create_dict_from_variables('abcd', 'efgh')
Run Code Online (Sandbox Code Playgroud)
这两个参数'abcd'和'efgh'不是命名变量。