pandas to dict

python pandas to dict

import pandas as pd
import json

b = [{'source': 'baidu', 'num': 61}, {'source': 'cctv', 'num': 14}, {'source': 'cntv', 'num': 3}, {'source': 'cntv', 'num': 1}, {'source': 'cntv', 'num': 1}]

if __name__ == '__main__':

    df =pd.DataFrame(b)

    c = df["num"].groupby(df['source']).sum()[:5]

    gg = pd.DataFrame(c)
    pandas_to_dict = gg.to_dict()
    pandas_to_json = gg.to_json()


    x = {'baidu': 61, 'cctv': 14, 'cntv': 5}
    y = {"微信": 0, "微博": 0,"头条": 0}

    #合并两个字典
    z = dict(x,**y)
    print(z)

    q= []
    dd ={'微信': 40, '微博': 0, '头条': 156, 'baidu': 610, 'cntv': 10}
    for v in dd:
        q.append({v:dd[v]})

    print(22,q)