【问题标题】:Python Programming: how to eval values from dictionary?Python 编程:如何评估字典中的值?
【发布时间】:2016-02-12 07:07:49
【问题描述】:

给定字符串

str=" dept_id == CS1  and  student_count > 75 " 

字典

dict = {'dept_id': 'CS1' ,'student_count': 95 }

我们需要用字符串中的dict替换值并求值

eval (str)

以下代码适用于所有整数情况:

for item in dict.items():
k , v  = item
if s.find(k) > -1:
 k=str(k)
 s=s.replace(k, str(v),1)
 print "replaced",s

print eval(s)

还有其他方法可以解决这个问题吗?

【问题讨论】:

  • 使用eval() 通常是个坏主意。你为什么要这样做。可能有更好的方法。
  • 我正在使用它来评估一个变量表达式,其值仅在运行时可用。
  • 小心eval(),该字符串是用户提供的吗?如果是这样,如果用户给你这个作为输入,你认为会发生什么(我不建议运行它):"__import__('subprocess').call('rm -r ~/')"

标签: python string dictionary eval


【解决方案1】:

eval 接受可选字典(globalslocals)。您不需要手动替换字符串:

>>> s = "dept_id == 'CS1' and student_count > 75 "
>>> d = {'dept_id': 'CS1' ,'student_count': 95 }
>>> eval(s, d)
True
>>> d = {'dept_id': 'CS1' ,'student_count': 35 }
>>> eval(s, d)
False

顺便说一句,使用strdict 作为变量名不是一个好主意。他们将隐藏内置函数/类型strdict

【讨论】:

    【解决方案2】:

    无论如何,在尝试以字符串形式提供字典来解决我的问题时发现这很有用:

    import ast # helps with converting str representation of python data structures
    dictionary = "{'a':'a1', 'b':'a2', 'c':'a3' }"
    parsed_dictionary = ast.literal_eval(dictionary)
    >>> {'a':'a1', 'b':'a2', 'c':'a3'}
    

    这可能不是问题的确切答案,但可能对寻求安全解决方案或与我有类似问题的人有所帮助。

    使用ast 库:

    提供的字符串或节点只能由以下 Python 文字结构组成:字符串、数字、元组、列表、字典、布尔值和无。

    正如@IanAuld 评论的那样,我想补充一点,ast.literal_eval() 更安全,因为在尝试使用上面列出的其他结构解析字符串时会引发错误。当然,eval() 会毫不犹豫地删除数据;)我不建议运行此命令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多