Python 如何更新键是字典中变量名的JSON字符串对象?

Python 如何更新键是字典中变量名的JSON字符串对象?,python,dictionary,Python,Dictionary,我有一个很长的字符串,看起来像一个字典,但其中许多键已被未定义的变量替换,例如: dict_1_str = '{a: "date", b: 7, c: {d: 5, e: "Hello There!"}}' 在实际的字典中,我有变量名和值 dict_2 = {"a": 1, "b": 2, "c": 3, "d": "General Kenobi!", &

我有一个很长的字符串,看起来像一个字典,但其中许多键已被未定义的变量替换,例如:

dict_1_str = '{a: "date", b: 7, c: {d: 5, e: "Hello There!"}}'
在实际的字典中,我有变量名和值

dict_2 = {"a": 1, "b": 2, "c": 3, "d": "General Kenobi!", "e": 5}
我想用底部字典中的值更新顶部字典中的键。我想我可以创建一个
dict_2
的键列表和一个
dict_2
的值列表,然后使用
exec()
对列表进行相等的计算,从而一次性设置所有变量-但我无法让它工作,如果可以的话,我宁愿避免
exec()

我尝试使用regex,但是
dict_1_str
中的许多字符串值都包含键/变量的名称。有什么优雅的方法可以做到这一点吗?

这个模块有帮助吗

您可以尝试以下代码以供参考

import demjson

dict_1_str = '{a: "date", b: 7, c: {d: 5, e: "Hello There!"}}'
dict_2 = {"a": 1, "b": 2, "c": 3, "d": "General Kenobi!", "e": 5}

s = demjson.decode(dict_1_str)
s.update(dict_2)
print(s)
# {'a': 1, 'b': 2, 'c': 3, 'd': 'General Kenobi!', 'e': 5}

r = demjson.encode(s)
print(r)
# {"a":1,"b":2,"c":3,"d":"General Kenobi!","e":5}


在这里,您可以阅读更多关于

的内容,它比使用
exec()
稍微安全一些,但是您可以使用并传递一个
globals
字典参数,该参数将阻止任何Python内置函数被传递到求值的表达式使用。(您的
dict_2
将是
locals
参数。)

输出:

{"1": "date", "2": 7, "3": {"General Kenobi!": 5, "5": "Hello There!"}}

我想我不明白。对于您显示的输入,期望的输出是什么?是的,这很好,谢谢。我很接近,只是不太明白如何使用locals参数。请注意,使用
locals
参数不是必需的
eval(dict_1_str,dict({''u_内置:None},**dict_2))
也可以,但更难理解(也更难写)。问题是在您的第一个注释中,当前str的键周围没有引号。我试过了。事实证明,dict1_str中的一些值也是不带引号的,我认为这种方法之所以失败,是因为它没有出现在最初的问题中。但我认为,当只需要更换钥匙时,它确实起作用。谢谢
import json 

# first I added quotes to surround property names in the string
dict_1_str = '{"a": "date", "b": 7, "c": {"d": 5, "e": "Hello There!"}}'
dict_2 = {"a": 1, "b": 2, "c": 3, "d": "General Kenobi!", "e": 5}

# This will convert the string to a dict
dict_1 = json.loads(dict_1_str)

# Here is a solution to merge two dict
dict_3 = {**dict_1, **dict_2}
import json

dict_1_str = '{a: "date", b: 7, c: {d: 5, e: "Hello There!"}}'
dict_2 = {"a": 1, "b": 2, "c": 3, "d": "General Kenobi!", "e": 5}

result = eval(dict_1_str, {'__builtins__': None}, dict_2)
print(json.dumps(result))
{"1": "date", "2": 7, "3": {"General Kenobi!": 5, "5": "Hello There!"}}