I have a Counter object in Python, which contains the following data:
{'a': 4, 'b': 1, 'e': 1}
I'd like to convert this to a JSON object with the following form:
[{'name':'a', 'value': 4} , {'name':'b', 'value': 1}, {'name':'e', 'value': 1}]
Is there any efficient way to do so?
You can use a list comprehension to convert the dictionary to a list of dictionaries. Example -
data = {'a': 4, 'b': 1, 'e': 1}
result = [{'name':key, 'value':value} for key,value in data.items()]
Demo -
>>> data = {'a': 4, 'b': 1, 'e': 1}
>>> result = [{'name':key, 'value':value} for key,value in data.items()]
>>> result
[{'name': 'a', 'value': 4}, {'name': 'b', 'value': 1}, {'name': 'e', 'value': 1}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With