Python 3 : Flatten Dictionary including lists

标签 python python-3.x list dictionary flatten

在 python 3 中是否有一种优雅的方法来实现这一点?它应该展平字典,同时将列表索引视为键,从而将它们包含在展平中。

在:

{
  "a": 1,
  "b": {
    "c": 2
  },
  "d": [3,4],
  "e": [
    {
      "f": 5
    },
    {
      "g": 6
    }
  ]
}

输出:

{
  "a": 1,
  "b.c": 2,
  "d.0": 3,
  "d.1": 4,
  "e.0.f": 5,
  "e.1.g": 6
}

背景:

  • 我们正在寻找一种方法来合并包含列表的嵌套字典
  • 可用的合并工具似乎总是使用追加策略或替换策略来合并列表
  • 但是,我们需要合并列表内的字典(如示例中所示)。例如,列表中的第一个字典应与列表中的第一个字典合并
  • 当前的方法是这样链接:展平 -> 合并 -> 取消展平。问题只是关于扁平的部分。从那以后我们发现,展平更加棘手
  • 我们最好使用现有的强大库

最佳答案

一种可能是利用 flatten-json图书馆。

它提供了 flatten、unflatten 和 unflatten_list 函数。

在您的用例中,需要 flatten 和 unflatten_list 函数。

from flatten_json import flatten, unflatten_list

d = {
  "a": 1,
  "b": {
    "c": 2
  },
  "d": [3,4],
  "e": [
    {
      "f": 5
    },
    {
      "g": 6
    }
  ]
}

desired_result = {
  "a": 1,
  "b.c": 2,
  "d.0": 3,
  "d.1": 4,
  "e.0.f": 5,
  "e.1.g": 6
}


d_flat = flatten(d, separator=".")
print(d_flat == desired_result)  # True

d_unflat = unflatten_list(d_flat, separator=".")
print(d == d_unflat)  # True

关于Python 3 : Flatten Dictionary including lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74157806/

相关文章:

python - Python 中 SciPy 树状图的自定义簇颜色(link_color_func?)

python - Pandas 数据帧值拒绝被评估为带有 `.apply(eval)` 的 float 。为什么?

python - 没有名为 'folium.plugins' 的模块,Python 3.6

python - 计算复杂度

r - 在 r 中合并具有相似内容的列表项?

python - 如何按特定顺序对字符串列表进行排序?

python - 从Python脚本连接到websocket服务器?

linux - Python简单的SSL通信

python-3.x - 如何确定 pip3 为非用户安装安装二进制文件/脚本的位置?

python - 用python字符串的ascii序数列表