简体   繁体   English

如何在 Python 中重新格式化 JSON / Dictionaries

[英]How can I reformat JSON / Dictionaries in Python

I have the below list -我有以下清单 -

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

I would like to reformat it like the below in Python -我想在 Python 中像下面这样重新格式化它 -

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

I did the below -我做了以下 -

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

But it outputs like this -但它的输出是这样的——

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

I would like these 2 lines to be a part of the same dictionary我希望这两行成为同一词典的一部分

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'}

I believe that it's best to try it first by yourself, and then post a question in case you don't succeed.我认为最好先自己尝试一下,然后再发布问题,以防万一不成功。 You should consider posting your attempts next time.下次您应该考虑发布您的尝试。

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

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