The Great god of PHP and Python came in to help convert a piece of code

Source: Internet
Author: User
Keywords Php python
Please translate this PHP code into Python code, thank you!

//倒序排序function my_sort($a,$b){    if ($a==$b) return 0;   return ($a<$b)?1:-1;}$arr = array('aaa'=>5,'bbb'=>3,'ccc'=>4);usort($arr,"my_sort");echo json_encode($arr);

Simply put, the array is sorted in reverse order and then converted to JSON format.

Reply content:

Please translate this PHP code into Python code, thank you!

//倒序排序function my_sort($a,$b){    if ($a==$b) return 0;   return ($a<$b)?1:-1;}$arr = array('aaa'=>5,'bbb'=>3,'ccc'=>4);usort($arr,"my_sort");echo json_encode($arr);

Simply put, the array is sorted in reverse order and then converted to JSON format.

The associative array in PHP is a ordered mapping (ordered mapping).
This means that the dictionary in Python is not exactly equal to the associative array.

Second, JSON does not support ordered mapping as I know it, so if you want to accomplish this task you might want to:

    1. Using an ordered mapping in Python: OrderedDict (Please refer to ordereddict)

    2. and turn it into OrderedDict listjson

    3. When you want to use the item, you must go json list back toOrderedDict

The following is the code of Python3 for you to participate in:

Password :

import jsonfrom collections import OrderedDict# using OrderedDictarr = {"aaa":5,"bbb":3,"ccc":4, "ddd":7}arr = OrderedDict(sorted(arr.items(), key=lambda item: item[1], reverse=True))# or you can create an OrderedDict directly:# arr = OrderedDict([('aaa', 5), ('bbb', 3), ('ccc', 4), ('ddd', 7)])print(arr)# listarr = list(arr.items())print(arr)# json dumpjson_arr = json.dumps(arr)print(json_arr)# json loadarr = OrderedDict(json.loads(json_arr))print(arr)

Results :

OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])[('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)][["ddd", 7], ["aaa", 5], ["ccc", 4], ["bbb", 3]]OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])

P.S. Any unclear areas are welcome to use the comments to tell me that we can discuss

import jsonarr={"aaa":5,"bbb":3,"ccc":4}print json.dumps(sorted(arr.values(),reverse=True))#'[5, 4, 3]'

Python code (after makeover)

#!/usr/bin/env python#encoding:utf-8import jsonif __name__ == '__main__':    myDict = {'aaa':5,'bbb':6,'ccc':777}    outDic = sorted(myDict.iteritems(), key=lambda asd: asd[1], reverse=True)    print '排序前的字典,类似于php的array'    print myDict    print '排序后json输出:'    print json.dumps(outDic)    

Output:

/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/luyh/www/python/lesson1/pysort.py排序前的字典,类似于php的array{'aaa': 5, 'bbb': 6, 'ccc': 777}排序后json输出:[["ccc", 777], ["bbb", 6], ["aaa", 5]]Process finished with exit code 0
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.