【问题标题】:elegant way to fill dictionary with variables in python在python中用变量填充字典的优雅方法
【发布时间】:2018-05-06 06:03:39
【问题描述】:

我正在寻找一种更优雅、更通用的方法来用变量填充字典:

dic = {}
fruit = 'apple'
vegetable = 'potato'

dic['fruit'] = fruit
dic['vegetable'] = vegetable

有没有更通用的方法而不使用引号中的变量名?

【问题讨论】:

标签: python


【解决方案1】:

如果引号是问题所在,那该怎么办?

fruit = 'apple'
vegetable = 'potato'

dic = dict(
    fruit = fruit,
    vegetable = vegetable
)

【讨论】:

    【解决方案2】:

    可能不是一个非常优雅的解决方案,但您可以使用 locals() 检索变量,然后将它们转换为字典。

    fruit = 'apple'
    vegetable = 'potato'
    dic = {key:value for key, value in locals().items() if not key.startswith('__')}
    

    这导致{'vegetable': 'potato', 'fruit': 'apple'}

    但是,我认为更好的选择是传递变量名称并创建一个字典,如this answer 中提供的那样:

    def create_dict(*args):
      return dict({i:eval(i) for i in args})
    
    dic = create_dict('fruit', 'vegetable')
    

    编辑:使用eval() 是危险的。更多信息请参考this answer

    【讨论】:

    • 你真的不应该推荐使用eval尤其是当它被用于评估函数的输入时。
    • 绝对!使用eval 是危险的,我相信我链接到的使用eval 的答案假定输入i 在运行eval() 之前已经过消毒和检查
    猜你喜欢
    • 2012-06-23
    • 2023-04-04
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2017-11-27
    相关资源
    最近更新 更多