Python:在类字典中更改值

kcwpcxri  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(98)

假设我有一个python中的分类字典,一个包含例如

from dict_class import linear, quadratic
example_dict = { "ex1" : [linear(a=1.0,
                                 b=2.0)],
                 "ex2" : [quadratic(a=1.0,
                                   b=2.0,
                                   c=3.0)]
                 }

其中dict_class.py是定义类的文件。
如何使用python编辑dict_ex.py文件中的字典值
为了清楚起见,我需要一个单独的python程序,可以运行它来修改包含字典的文件。
Python版本3.9.18
我试过使用jsonpickle,但这会通过将类转换为字典条目的额外成员来处理它们,例如。"py/object" : "dict_class.linear"

piok6c0g

piok6c0g1#

您可以利用ast(抽象树)模块将文件的内容解析为AST,在那里我们可以遍历AST并找到我们需要修改的内容。在下面的代码中,我使用了astunparse,这个模块允许我将ast解析为字符串。
关于dict_ex.py的结构和文本:

import ast
import astunparse

def modify_dict_value(filename, key, new_value):
    # Read the dictionary from file
    with open(filename, 'r') as f:
        content = f.read()

    # Parse the code into an AST
    parsed = ast.parse(content)

    # Walk through the AST and find the dictionary
    for node in ast.walk(parsed):
        
        # "ast.Assign" is the node type for assignments (e.g. "a = 1", in this case, we're looking for the "example_dict" assignment")
        if isinstance(node, ast.Assign): 
          # node.targets is a list of targets, in this case, we're looking for the "example_dict" target (x=5, "x" is the "target")
          for target in node.targets:
              
              # "ast.Name" is the node type for names (e.g. "a" in "a = 1"), we're trying to find the "example_dict" name
              if isinstance(target, ast.Name) and target.id == 'example_dict':

                  # Loop through the keys and values of the dictionary we just found
                  for k, v in zip(node.value.keys, node.value.values):

                      # Check if the node is a string and if the string is the key we're looking to modify
                      if isinstance(k, ast.Str) and k.s == key:

                          # Modify the value of the dictionary, considering each key has a value that is a list, and each of these lists has only one item ("linear" or "quadratic") 
                          v.elts[0] = ast.parse(new_value).body[0].value
                          break

    # write the modified AST back into the source file, "astunparse" is used to convert the AST back into a string
    with open(filename, 'w') as f:
        f.write(astunparse.unparse(parsed))

# example usage
modify_dict_value('dict_ex.py', 'ex1', 'linear(a=5.0, b=6.0)')

**请注意:**在这种情况下,我们假设每个键都有一个列表值,并且每个列表只包含一个项(在您的情况下是“线性”或“二次”)。

相关问题