从变量列表创建字典

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)


Chr*_*gan 7

您可以使用locals,但我建议您不要使用它。明确地做。

>>> import this
[...]
Explicit is better than implicit.
[...]
Run Code Online (Sandbox Code Playgroud)

如果你明确地这样做,你的代码通常会更好、更可预测、更不容易被破坏并且更容易理解。

  • 我已经很长时间没有解决我在 python 中无法完成的事情了。我正在编写一些需要为其他函数返回大量参数的函数。返回的字典几乎与变量名称相同,因此当我明确写入密钥时,我很有可能会犯错。但是我祖父曾经告诉我,生活并不容易 :) (2认同)

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'不是命名变量。

  • 不正确(参见 Vasus 的回答)并且没有帮助。请参阅 Not_a_Golfer 的 pythonic 答案。 (2认同)