Search code examples
pythonpython-3.xstringeval

Python: update dict string that has placeholders?


Consider this string: "{'a': A, 'b': B, 'c': 10}". Now I want to update this "string" and add new key d with let say value 20, so result would be "{'a': A, 'b': B, 'c': 10, 'd': 20}"

Normally, you could just eval string (eval or literal_eval) into dict, update the way you want and convert it back to string. But in this case, there are placeholders, which would not be recognized when evaluating.

What would be best way to update it, so old values are kept the same, but "dict-string" is updated properly?


Solution

  • This by no means a best solution but here is one approach:

    import re
    
    dict_str = "{'a': A, 'b': B, 'c': 10}"
    
    def update_dict(dict_str, **keyvals):
        """creates an updated dict_str
    
            Parameters:
                dict_str (str): current dict_str
                **keyvals: variable amounts of key-values
    
            Returns:
                str:updated string
    
        """
        new_entries = ", ".join(map(lambda keyval: f"'{keyval[0]}': {keyval[1]}", keyvals.items())) # create a string representation for each key-value and join by ','
        return dict_str.replace("}", f", {new_entries}{'}'}")   # update the dict_str by removing the last '}' and add the new entries
    
    

    output:

    updated = update_dict(dict_str,
        d = 20,
        e = 30
    )
    print(updated)
    
    {'a': A, 'b': B, 'c': 10, 'd': 20, 'e': 30}
    
    some_dict = {
        'g': 2,
        'h': 3
    }
    
    updated = update_dict(dict_str,
        **some_dict
    )
    print(updated)
    
    {'a': A, 'b': B, 'c': 10, 'g': 2, 'h': 3}