【问题标题】:How to append the list of dictionary to same list in python?如何将字典列表附加到python中的相同列表?
【发布时间】:2021-04-26 13:52:09
【问题描述】:

我有一个带有嵌套值的 JSON。我需要删除嵌套字段的键,并且需要将值保留为纯 JSON。

JSON(我的 JSON 结构)

[
  {
"id":"101",
"name":"User1",
"place":{ 
    "city":"City1",
    "district":"District1",
    "state":"State1",
    "country":"Country1" 
    },
"access":[{"status":"available"}]
  }
]

我需要得到 JSON 输出为:

预期输出:

[
 {
 "id":"101",
 "name":"User1",
 "city":"City1",
 "district":"District1",
 "state":"State1",
 "country":"Country1" 
 "access":[{"status":"available"}]
 }
]

我需要的是:

  1. 我需要解析 JSON
  2. 从 JSON 中获取 Place字段
  3. 删除键和括号并将值附加到现有的

Python

for i in range(0,len(json_data)):
   place_data = json_data[i]['place']
   print(type(place_data)) #dict
   del place_data['place'] 

在 python 中获得预期输出的任何方法。?

【问题讨论】:

    标签: python json python-3.x list dictionary


    【解决方案1】:

    通过更新多个“键”来完成此操作的另一种方法... 这仅适用于原始问题中描述的单个嵌套级别

    def expand(array):
        flatten = list()
        for obj in array:
            temp = {}
            for key, value in obj.items():
                if isinstance(value, dict):
                    temp.update(value)
                else:
                    temp.update({key:value})
            flatten.append(temp)    
        return flatten  
    

    【讨论】:

      【解决方案2】:

      实现这一目标的一种方法是

      for i in json_data:
          i.update(i.pop("place"))
      

      【讨论】:

        猜你喜欢
        • 2020-12-06
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2013-03-27
        • 2019-03-29
        • 1970-01-01
        相关资源
        最近更新 更多