python 根据字典中的key,value进行排序

#coding=utf-8

import requests,json,collections,base64,datetime
def sort(datas):
    data=json.dumps(datas)#dumps是将dict转化成str格式,loads是将str转化成dict格式。
    print u"data %s" % data
    data=json.loads(data)
    print  type(data)
    msg=data['msg'] #获取msg中key,value
    print msg
    print  type(msg)
    keys=msg.keys()
    msgkv={}
    for  k,v  in msg.items():
        msgkv[k]=v
    print msgkv
    kv=sorted(msgkv.items(),key=lambda item:item[0])#现在是按照key首字母进行排序,如果想按照value进行排序只需要将item[0],改为item[1]
    #print u"排序之后的字典 %s" % kv
    kv2={}
    mg=""
    for  k,v  in kv:
        kv2[k]=v
        mg=mg+k+'='+v+'&'
    mg=mg[:-1]
    #print u'连接符& %s'% mg
    print u"mg %s " % mg
    return mg
msg={
    "msg": {
        "transTime": "20170110000000",
        "name": "张三",
        "accType": "00",
        "cardNo": "622586842111132567",
        "cnaps": "123456",
        "bankName": "银行",
        "certType": "00",
        "certNo": "350128199525362156",
        "phoneNo": "13665588962",
        "transAmt": "1",
        "currency": "CNY",
        "backUrl":"http://xxx/xxx",
        "proceedUse": "代扣",
        "businessCode": "10400"
    },
    "merchCode": "898000001000001",
    "orderId": "000000000000001",
    "transCode": "600101",
    "signature": "ImdJA+kA7FkDrEQuWSmbPqFkSF7UyWMX0/udozVP2grNrJVqgXcUBAbEP0jHPeSKenKw9a9lrBbLivTemIIuDk/Xywap/+9TYz5jQwmO/DegIuvHAi9JY6J3orSCl0eHM+7wGydxNnqoOBZcST1GzzYgHBs9fmWYWtpkX6cnFBOfJ/vFXNbiSzI8byNSae2MMbn7RSr9ymCNxVrBIPtN9x6WtDtrTGo/5iW1ZOSb5mqxyA8dVnebTjwWEnGmdu2"
}
mg1=sort(msg)

 

posted @ 2018-11-15 14:37  天空是我喜欢的颜色  阅读(1665)  评论(1编辑  收藏  举报