【问题标题】:How to combine dict elements in list while changing nested json contents?如何在更改嵌套 json 内容时合并列表中的 dict 元素?
【发布时间】:2021-02-21 19:24:51
【问题描述】:

我现在拥有的:

list1 = [{"nested_json_a": "nested_values_a"}, {"nested_json_b": "nested_values_b"}, {"nested_json_c": "nested_values_c"}, {"nested_json_d": "nested_values_d"}]

我想要做的基本上是将nested_json_anested_json_c 以及nested_json_bnested_json_d 组合在一起。这里要注意的是,最终整个列表中只需要两个元素,输出如下所示:

list1 = [
   {
      "combined_a_c":{
         "nested_json_a":"nested_values_a",
         "nested_json_c":"nested_values_c"
   },
      "combined_b_d":{
         "nested_json_b":"nested_values_b",
         "nested_json_d":"nested_values_d"
      }
   }
]

最有效的方法是什么?一段时间以来一直陷入困境并为此苦苦挣扎。

【问题讨论】:

  • 您的输出不是有效的 JSON 或有效的字典列表
  • 现在正确吗?我想说的话没有意义吗?本质上,我试图将 a 和 c 列表元素与 b 和 d 组合在一起,同时将内容嵌套在一个 JSON 中,并使用新的组合总体名称
  • 读取json文件,在python中进行修改,覆盖整个json文件。
  • 我对JSON格式说实话不太挑剔,只要有基本的组合信息思路就行了
  • @KennyOstrom 但我将如何在 python 中执行更改是我的问题。我打算自动化这部分,所以不能手动执行此操作

标签: python json list dictionary


【解决方案1】:
from collections import defaultdict as dd
nested = dd(dict)
for d in list1:
    for k in d:
        if k in keys_dict: # you need to decide what to do with a key that doesn't have a combined key to move to
            nested[keys_dict[k]][k]=d[k]


这将返回一个字典而不是字典列表

defaultdict(<class 'dict'>, {'combined_a_c': {'nested_json_a': 'nested_values_a', 'nested_json_c': 'nested_values_c'}, 'combined_b_d': {'nested_json_b': 'nested_values_b', 'nested_json_d': 'nested_values_d'}})

如果它是一个字典列表很重要,请转换它

new_list1= []
for k in nested:
    new_list1.append({k:nested[k]})


【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2021-06-16
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2021-11-01
    • 2018-12-10
    • 2016-11-14
    相关资源
    最近更新 更多