简体   繁体   English

将字典列表合并到 json

[英]Merging a list of dictionaries to json

I am trying to merge a list of dictionaries into a single json object to be consumed by another json parser.我正在尝试将字典列表合并到单个 json object 以供另一个 json 解析器使用。

Here is my list which I fetched from a requests.get :这是我从requests.get获取的列表:

list = [{"name":"New York USA"}, {"id":446}]

Desired Output:所需的 Output:

{
  "org": {
    "name": "New York USA",
    "id": 446
  }
}

Another solution would be Using dictionary comprehension ( Note : This solution will work even if dict has multiple keys and values)另一种解决方案是使用字典理解注意:即使 dict 有多个键和值,此解决方案也可以工作)

list = [{"name":"New York USA"}, {"id":446}]
data = {}
data['org'] = {key:value for item in list for key, value in item.items()}
print(data)

output: {'org': {'name': 'New York USA', 'id': 446}}

You can use the builtin json library您可以使用内置的json 库

import json

list_of_dicts = [{},{}]

json_rep = json.dumps(list_of_dicts)

First merge your all dictionaries in list then, make a new dictionary thn dumps it with json.please try this below首先将所有字典合并到列表中,然后制作一个新字典,然后将其与 json 一起转储。请在下面尝试

import json
list = [{"name":"New York USA"}, {"id":446}]
def Merge(dict1, dict2): 
   res = {**dict1, **dict2} 
   return res 
dic=Merge(list[0],list[1])
print(dic)
new_json={'org':dic}
json_rep = json.dumps(new_json)
print(json_rep)

output output

'{"org": {"name": "New York USA", "id": 446}}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM