i have the following groupby results as a dataframe called grouped:
long_url counts
3 reddit.com 542
2 linkedin.com 529
4 twitter.com 525
1 google.com 502
0 github.com 476
5 youtube.com 469
i would like to turn the results into a json dict array like this:
[{"reddit.com": 542}, {"linkedin.com" : 529}]
currently i have
import json
grou=json.dumps(grouped.reset_index(drop=True).to_dict(orient='records'))
grou
it gives me:
'[{"long_url": "reddit.com", "counts": 542}, {"long_url": "linkedin.com", "counts": 529}, {"long_url": "twitter.com", "counts": 525}, {"long_url": "google.com", "counts": 502}]'
however it differs with what i wanted to achieve.
is there any way to accomplish without the headers??
3
Answers
You can iterate the
values
of yourgrouped
dataframe to make a list of dicts:Output:
You can do it like this:
Output:
Run it here
There are couple of ways to achieve that, and the above answers are all making sense. Additionally, you can achieve by using the combination of dict and zip
Then you will see the results: