在JavaScript中,您可以像这样初始化对象:
{ a, b }
其中a
和b
被声明为变量。初始化将在新对象中使用它们的值。
Python中有类似的东西吗?
答案 0 :(得分:1)
您可以实施自己的口译员来满足以下要求:
import re
# Set up local variable enviroment
#
# without the following assignment expressions,
# my lambda expression will return an empty dict
a = 1
b = 2
print((lambda str: (lambda f, z: { **f(globals(), z), **f(locals(), z) })(lambda s, t: { k: v for k, v in s.items() if t(k) },(lambda l: lambda k: k[0] is not '_' and k[-1] is not '_' and k in l)(re.sub(r'[\s\{\}]+', '', str).split(','))))('{ a, b }'))
输出将是:
{'a': 1, 'b': 2}
但是convert
只能消化您的简单用例,而没有嵌套结构。
更多人性化版本:
import re
example_string = '{ a, b }'
def convert_string_to_dict(example_string):
list_of_variables = re.sub(r'[\s\{\}]+', '', example_string).split(',')
def validate(key):
return key[0] is not '_' \
and key[-1] is not '_' \
and key in list_of_variables
def make_dict_from_environment(env):
return { key: val for key, val in env.items() if validate(key) }
merge_two_dicts = { **make_dict_from_environment(globals()), **make_dict_from_environment(locals()) }
return merge_two_dicts
# Set up local variable enviroment
#
# without the following assignment expressions,
# `convert_string_to_dict('{ a, b }')` will return an empty dict
a = 1
b = 2
print(convert_string_to_dict(example_string))
答案 1 :(得分:0)
似乎python不支持此功能。但是,您可以编写某种程度上模仿此功能的库。参见上面的@KaiserKatze答案
答案 2 :(得分:-1)
您可以这样声明Python字典:
dictionary = {'name':'test','value':2.5}