Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Convert a Counter object to a json object with added key names

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?

like image 218
neif Avatar asked Mar 15 '23 10:03

neif


1 Answers

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}] 
like image 133
Anand S Kumar Avatar answered Apr 26 '23 11:04

Anand S Kumar