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:
Using an ordered mapping in Python: OrderedDict
(Please refer to ordereddict)
and turn it into OrderedDict
list
json
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