skip to Main Content

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


  1. You can iterate the values of your grouped dataframe to make a list of dicts:

    groups = [{url: count} for [url, count] in grouped.values]
    json.dumps(groups)
    

    Output:

    '[{"reddit.com": 542}, {"linkedin.com": 529}, {"twitter.com": 525}, {"google.com": 502}, {"github.com": 476}, {"youtube.com": 469}]'
    
    Login or Signup to reply.
  2. You can do it like this:

    import json
    
    your_json = '[{"long_url": "reddit.com", "counts": 542}, {"long_url": "linkedin.com",   "counts": 529}, {"long_url": "twitter.com", "counts": 525}, {"long_url": "google.com", "counts": 502}]'
     
    content = json.loads(your_json)
    
    my_json = [{item['long_url']: item['counts']} for item in content]
    
    print(my_json) 
    

    Output:

    Run it here

    [{'reddit.com': 542}, {'linkedin.com': 529}, {'twitter.com': 525}, {'google.com': 502}]
    
    Login or Signup to reply.
  3. 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

    df = grouped.reset_index()
    dict(zip(df['long_url'], df['counts']))
    

    Then you will see the results:

    {'reddit.com': 542,
     'linkedin.com': 529,
     'twitter.com': 525,
     'google.com': 502,
     'github.com': 476,
     'youtube.com': 469}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search