【问题标题】:How can I reformat JSON / Dictionaries in Python如何在 Python 中重新格式化 JSON / 字典
【发布时间】:2019-12-26 15:15:38
【问题描述】:

我有以下列表 -

[{'metric': 'sales', 'value': '100', 'units': 'dollars'}, 
{'metric': 'instock', 'value': '95.2', 'units': 'percent'}]

我想在 Python 中像下面这样重新格式化它 -

{'sales': '100', 'instock': '95.2'}

我做了以下 -

a = [above list]
for i in a:
    print({i['metric']: i['value']})

但它的输出是这样的 -

{'sales': '100'}
{'instock': '95.2'}

我希望这两行成为同一个字典的一部分

【问题讨论】:

  • 我编辑了帖子并添加了我尝试过的细节。估计我来晚了
  • 欢迎来到 StackOverflow。 On topichow to ask 和 ...the perfect question 在此处申请。 StackOverflow 是针对特定 编程问题的知识库——不是设计、编码、研究或教程资源。正如您所注意到的那样,不加尝试地发帖是一种非常可靠的方式来获得反对票。

标签: python json dictionary


【解决方案1】:
d = [{'metric': 'sales', 'value': '100', 'units': 'dollars'}, 
{'metric': 'instock', 'value': '95.2', 'units': 'percent'}]

new_d = {e["metric"]: e["value"] for e in d}
# output: {'sales': '100', 'instock': '95.2'}

我认为最好先自己尝试一下,然后再发问题以防万一不成功。您应该考虑下次发布您的尝试。

【讨论】:

  • 谢谢@AdamGold。我编辑了帖子并添加了有关我尝试过的内容的详细信息。估计我来晚了
猜你喜欢
  • 2015-08-20
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
  • 2011-02-14
  • 2016-12-06
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
相关资源
最近更新 更多