【问题标题】:How to convert list of dict to json in python?如何在python中将dict列表转换为json?
【发布时间】:2020-07-19 16:23:24
【问题描述】:

我有一个 JSON 列表,我想将其转换为单个 JSON,我尝试使用 json.dumps,但结果仍然给出了 JSON 列表。

"response":[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]

我想要它的形式

"response":{"sent":46,"drafts":2,"completed":48,"pending":1}

你能帮我解决这个问题吗?

【问题讨论】:

  • 那么,如果您有一个列表,如果 dictionaries 并且您想将它们合并到一个 dictionary 中?
  • 假设所有的键都是唯一的,你可以使用像{"response": {k: v for item in data['response'] for k, v in item.items()}}这样的dict理解
  • 请您指导一下,是的,我想将字典列表转换为一个字典
  • @ChrisDoyle,嘿,谢谢
  • 你的输出格式应该是{'response': [{'sent': 46}, {'drafts': 2}, {'completed': 48}, {'pending': 1}]}

标签: python-3.x list dictionary


【解决方案1】:

你可以使用:

from itertools import chain
r = {"response" :[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]}


r['response'] = dict(chain(*map(dict.items, r['response'])))
# same with:
# r['response'] = dict(chain.from_iterable(map(dict.items, r['response'])))
r

输出:

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

或者你可以使用字典理解:

r['response'] = {k: v for d in r['response'] for k, v in d.items()}

输出:

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

【讨论】:

    【解决方案2】:

    你可以使用

    json_obj = {"response":[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]}
    {k: {list(i.keys())[0]: list(i.values())[0] for i in v} for k, v in json_obj.items()}
    

    会输出

    {'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2017-07-04
      • 1970-01-01
      • 2021-10-10
      相关资源
      最近更新 更多