JS风格的字典初始化快捷方式?

问题描述 投票:1回答:3

在JavaScript中,您可以初始化对象,如下所示:

{ a, b }

其中ab被声明为变量。初始化将在新对象中使用它们的值。

Python中有类似的东西吗?

javascript python
3个回答
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))

0
投票

看来python不支持这个。但是,您可以编写一个有点模仿此功能的库。请参阅上面的@KaiserKatze答案


-1
投票

你可以像这样声明一个Python字典:

dictionary = {'name':'test','value':2.5}

© www.soinside.com 2019 - 2024. All rights reserved.