首页 > 解决方案 > JS风格的字典初始化快捷方式?

问题描述

在 JavaScript 中,你可以像这样初始化一个对象:

{ a, b }

whereab是声明的变量。初始化将在新对象中使用它们的值。

Python中有类似的东西吗?

标签: javascriptpython

解决方案


您可以实现自己的解释器来满足这样的要求:

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))

推荐阅读