如何在 R 中合并 2 python 个词典?

How do I merge 2 python dictionaries in R?

我在 R 中使用 Tensorflow 包,我需要合并 2 个字典来创建一个 feed.dict。

在pythonthis is simple。在 R 中完成这项工作的最佳方法是什么?由于我无法控制的原因,我无法直接使用 Python。

编辑

我想出了以下解决方法。如果有人有更好的解决方案请post回答。

mergeDictionaries = function(dict1, dict2){
  list1 = py_to_r(dict1)
  list2 = py_to_r(dict2)
  r_to_py(c(list1, list2))
}

新创建的 reticulate 包为 python 模块提供 R 接口,可用于您的案例。假设你已经安装了 Python 3,你可以 运行 下面的代码块,

py_str = "x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = dict(list(x.items()) + list(y.items()))"


py_dict = reticulate::py_run_string(code = py_str, local = FALSE, convert = FALSE)
py_dict$z

结果会是,

{'a': 1, 'b': 10, 'c': 11}